Why should i use Ruby on Rails?


Previous yesterday(22 Feb, 2014) we had Delhi NCR Ruby Meetup on Open Source Saturday – How can I contribute to Ruby on Rails?. There i had opportunities to meet few college student, Once of them asked to me – Why should i use Ruby on Rails? Yeah, That’s really good question ūüôā So let’s talk, why should we use Ruby on Rails when dozen of language and frameworks are available.

1. Ruby on Rails provides a consistent approach to build your web applications. If you have already experienced with other web development language or framework, you can understand, how tough it was process, you typically need to survey and ask with expert to choose your various software components to solve the common architectural problems of persistence,  build scripts, testing, logging, database setup, application configuration, web tier components and rest of software life cycle. Using the Ruby on Rails framework these decisions are already made for you, now you can spend more time to understanding software business problem and quickly build a working prototype. By using Rails you become productive in minutes not weeks or months.

2. Ruby on Rails follow CONVENTION OVER CONFIGURATION pragmatic philosophy, this apply in all layers of your software development architecture with the highest productivity gains noticeable in the relationship between the model and the database(ORB- Object Relationship Model). Once the developer understands the rules and constraints, Rails MVC magically connects your view to your controller and model, and your model to the database. That‚Äôs awesome .!! You do not have to write any script or tool to manage all this ==> MVC ‚Äď Model View and Controller.

 

rubyonrails

3. When we talk about OOP’s, Ruby is a fully featured object-oriented language and in addition Ruby come with mix-ins modules which contain independent code to inject into your classes and block. Ruby is an extremely dynamic/run time language, which means that code can be generated and executed on the fly. It’s dynamic nature includes the definition of new classes & methods, as well as the overloading of operators etc. Apart from this you can re-open, redefine and removed existing classes on fly.

4. Unlike other web language and framework, rails has build in templating support, json/xml document and email service.

5. Rails comes with ActiveRecord, Association and ActiveModel(object relationship mapping), which provides seamlessly persisted interface to database like transactions, inheritance, validation, scope and caching.

6. Rails includes support for a variety of web technologies like JavaScript libraries, JQuery, REST, Embedded ruby, HAML, CoffeeScript etc. with configuration in development, test and production environments. If you are planing your application into Web 2.0 space, Rails provides a rich abstracted interface to implementing AJAX operations.

7. Most important rails gives us flexibilities to perform database migration and rollbacks between environments and across development until project at mature stage. However with the Rails framework you will be delighted with the implementation of database migrations for applying and rolling back database changes. You only need to enter your update and rollback scripts in Ruby, framework understands the current version & can move forwards or backwards to any database version.

8. Getting started with Rails is easy as generators/migration will propel you along. DRY(Don’t Repeat Yourself) principle of Rails encourage experience developer to write less code by using the metaprogramming features of Ruby. Overall less code to write means higher productivity, less bugs and minimum complexity.

I hope you convinced, Still doubt? Please go through below links:

http://www.skilledup.com/learn/programming/4-reasons-learn-ruby-first-programming-language/
http://www.techrepublic.com/blog/10-things/10-reasons-why-you-should-learn-ruby-on-rails/3060/
http://blog.teamtreehouse.com/reasons-why-every-web-designer-needs-to-learn-rails

http://articles.businessinsider.com/2011-05-11/tech/30035869_1_ruby-rails-custom-software

Have question? feel free to comment. ūüôā

Advertisements

Streaming Files to the Browser with Ruby


I’m trying to find an efficient way to watch the server log on a web page. I don’t mind building a gem; I just want to work out the best way to do it.

Is there a way to keep a stream open to a file with Ruby (not any frameworks) and to the browser? Or will it have to be done by polling the file every x seconds?

That was the question, what i asked Streaming Files to the Browser with Ruby over stackoverflow. I done this job using cramp framework that is written by Pratik Naik.

Cramp:-

Cramp is a fully asynchronous real-time web application framework in Ruby. It is built on top of EventMachine and primarily designed for working with larger number of open connections and providing full-duplex bi-directional communication.

Solution:

1.Ruby 1.9.2+ is the preferred version of Ruby for running Cramp. Installation process is quite straight forward:

$ gem install cramp

2. Create new cramp applicaton

$cramp new my_logger

3. Edit home action and write log solution here

class HomeAction < Cramp::Action
  def start
    File.open("/home/ubuntu/demo/log/development.log", "r").each_line do |line|
      render line
    end
    finish
  end
end

4. And then start the server:

$ bundle exec thin --timeout 0 -R config.ru start

You should be greeted with ‚Äúlogs‚ÄĚ on browsing to http://0.0.0.0:3000/

Thats it,  Thanks Pratik Naik for such a great work.

Ruby String


This post is addition to previous post Ruby Symbols and Strings more specific to Ruby string methods That’s useful to our regular coding practice.

String

“A string is a group of characters that typically make up human readable words or sentences. Because strings are essentially the mechanism by which applications communicate with their users it is inevitable that string manipulation is a key part of programming”.

1. Freezing Objects

The freeze method in class Object prevents you from changing an object, effectively turning an object into a constant. After we freeze an object, an attempt to modify it results in TypeError. For details you can refer previous post Ruby Strings and Symbols point 8th.

1.9.2p320 :277 > test = ‚ÄúThis is ruby string‚ÄĚ
=> ‚ÄúThis is ruby string‚ÄĚ
1.9.2p320 :278 > test.upcase!
=> ‚ÄúTHIS IS RUBY STRING‚ÄĚ
1.9.2p320 :280 > test.freeze
=> ‚ÄúTHIS IS RUBY STRING‚ÄĚ
1.9.2p320 :281 > test.downcase!
RuntimeError: can’t modify frozen string
from (irb#1):281:in `downcase!’
from (irb#1):281

2. frozen?

A method frozen? tells you whether an object is frozen or not.

1.9.2p320 :001 > a = “This is String”
=> “This is String”
1.9.2p320 :002 > a.frozen?
=> false
1.9.2p320 :004 > a.freeze
=> “This is String”
1.9.2p320 :005 > a.frozen?
=> true

3. Comparing two strings for equality

Below are the three frequent used methods.

1.9.2p320 :011 >¬†¬† a = “I am ruby developer”
=> “I am ruby developer”
1.9.2p320 :012 > b = “I am rails developer”
=> “I am rails developer”

a). ==

The most common one is == (double equals sign).

1.9.2p320 :016 >   a == b
=> false

b).String.eql?

Tests two strings for identical content. It returns the same result as ==.

1.9.2p320 :018 > a.eql?(b)
=> false

c).String.equal?

Tests whether two strings are the same object.

1.9.2p320 :019 > a.equal?(b)
=> false

4.Parse lines in a String object with #each_line or #lines, instead of #each

1.9.2p320 :056 >¬†¬† s1 = “Mutable objects can be changed after assignment while immutable objects can only be overwritten”
=> “Mutable objects can be changed after assignment while immutable objects can only be overwritten”
1.9.2p320 :057 > s1.each {|a| p a}
NoMethodError: undefined method `each’ for #<String:0x92c1cf4>
from (irb):57
from /usr/local/rvm/rubies/ruby-1.9.2-p320/bin/irb:16:in `<main>’
1.9.2p320 :058 > s1.each_line {|a| p a}
“Mutable objects can be changed after assignment while immutable objects can only be overwritten”
=> “Mutable objects can be changed after assignment while immutable objects can only be overwritten”
1.9.2p320 :059 > s1.lines {|a| p a}
“Mutable objects can be changed after assignment while immutable objects can only be overwritten”
=> “Mutable objects can be changed after assignment while immutable objects can only be overwritten”

5. String#ord returns the UTF-8 index

1.9.2p320 :069 > a = ‘A’
=> “A”
1.9.2p320 :070 > b = “c”
=> “c”
1.9.2p320 :071 > c = “ABC”
=> “ABC”
1.9.2p320 :072 > a.ord
=> 65
1.9.2p320 :073 > b.ord
=> 99
1.9.2p320 :074 > c.ord
=> 65

6. String#codepoints to get an enumerator of each codepoint (UTF-8 index)

1.9.2p320 :081 > s1.codepoints.each {|a| p “#{a}”}
“77”
“117”
“116”
“97”
“98”
“108”
“101”
“32”
=> “Mutable”

7.String#clear clears to an empty string in place.

1.9.2p320 :094 >   s1
=> “Mutable objects can be changed after assignment while immutable objects can only be overwritten”
1.9.2p320 :095 > s1.clear
=> “”

8. String#length returns length in chars.

1.9.2p320 :100 >   s1.length
=> 95

9. String#encoding returns the relevant Encoding object for the string.

1.9.2p320 :102 > s1.encoding
=> #<Encoding:UTF-8>

Here just I limelight few important and new feature that are part of ruby 1.9.3 ūüôā

Ruby Symbols and Strings


I had good timing with one of rubyist yesterday. He asked me, what is major difference between Ruby string and symbols. Honestly speaking i had no words expect symbols definition(Symbols are immutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten). Finally he explained me with a nice example, Again i googled and come up with few new addition. That what i want to explain here, May it will help some one.

All are self explanatory, put a comment if need more details.

1. Single word String and Symbol

1.9.2p320 :226 > “test”
=> “test”
1.9.2p320 :227 > :test
=> :test

2. Multiple words String and Symbol

1.9.2p320 :230 > “test string”
=> “test string”
1.9.2p320 :231 > :”test string”
=> :”test string”

3. Symbol may also contain special characters like string

1.9.2p320 :234 > :”test string #”
=> :”test string #”
1.9.2p320 :235 > :”test string $”
=> :”test string $”

4. Convert string to Symbol:

1.9.2p320 :239 > “I am Ruby developer”
=> “I am Ruby developer”
1.9.2p320 :240 > “I am Ruby developer”.to_sym
=> :”I am Ruby developer”
1.9.2p320 :241 > “I am Ruby developer”.intern
=> :”I am Ruby developer”

5. Convert symbol to String:

1.9.2p320 :244 > :”I am Rails developer”
=> :”I am Rails developer”
1.9.2p320 :245 > :”I am Rails developer”.to_s
=> “I am Rails developer”

6. Strings are mutable(Mutable objects can be changed after assignment):

1.9.2p320 :250 > text = “I belongs to the”
=> “I belongs to the”
1.9.2p320 :251 > puts text << ” India”
I belongs to the India

7. Symbols are immutable(immutable objects can only be overwritten):

1.9.2p320 :252 > text = :”I belongs to the”
=> :”I belongs to the”
1.9.2p320 :253 > puts text << :” India”
NoMethodError: undefined method `<<‘ for :”I belongs to the”:Symbol
from (irb#1):253

8.Frozen Strings

We can freeze the String and thus making it immutable. Once a String is frozen it cannot be changed.

1.9.2p320 :277 > test = “This is ruby string”
=> “This is ruby string”
1.9.2p320 :278 > test.upcase!
=> “THIS IS RUBY STRING”
1.9.2p320 :280 > test.freeze
=> “THIS IS RUBY STRING”
1.9.2p320 :281 > test.downcase!
RuntimeError: can’t modify frozen string
from (irb#1):281:in `downcase!’
from (irb#1):281

9. String Performance:

Because Strings are mutable, the Ruby interpreter never knows what that String may hold in terms of data. As such, every String needs to have its own place in memory. We can see this by creating some Strings and printing their object id.

1.9.2p320 :295 > puts “This is string performance test”.object_id
76899900
=> nil
1.9.2p320 :296 > puts “This is string performance test”.object_id
76884690
=> nil
1.9.2p320 :297 > puts “This is string performance test”.object_id
76870210
=> nil
1.9.2p320 :298 > puts “This is string performance test”.object_id
76855080
=> nil
1.9.2p320 :299 > puts “This is string performance test”.object_id
76842070
=> nil

NOTE: Our object id’s will be different then the ones above.

What we see above might not seem like a big issue, but behind the scenes is some heavy waste. To understand why, we first have to understand what is going on under the hood. An abridged explanation is as follows:

  1. First, a new String object is instantiated with the value of "This is string performance test".
  2. The Ruby interpreter needs to look at the heap (your computers memory), find a place to put the new string and keep track of it via its object id.
  3. The String is passed to the puts method, and output to the screen.
  4. The Ruby interpreter sees that the String will not be used again as it is not assigned to a variable, and marks it for destruction.
  5. Back to step one four more times.

Conclusion: In above example, we are creating a new object, storing and ultimately destroying.

10. Symbol Performance:

1.9.2p320 :301 > puts :”This is string performance test”.object_id
233758
=> nil
1.9.2p320 :302 > puts :”This is string performance test”.object_id
233758
=> nil
1.9.2p320 :303 >
1.9.2p320 :304 > puts :”This is string performance test”.object_id
233758
=> nil
1.9.2p320 :305 > puts :”This is string performance test”.object_id
233758
=> nil
1.9.2p320 :306 > puts :”This is string performance test”.object_id
233758

In above, every Symbol shares the same object id, and as such the same space on the heap. To further increase performance, Ruby will not mark Symbols for destruction, allowing you to reuse them again and again. As Symbols stay in memory throughout the programs operation, we can quickly snag them from memory instead of instantiating a new copy every time. In fact, Symbols are not only stored in memory, they are also keep track of via an optimized Symbols dictionary.

10. We can see all Symbol by running the below command.

1.9.2p320 :340 > puts Symbol.all_symbols.inspect

[:example, :”test string”, :”test string #”, :”test string $”, :”I am Ruby developer”, :”I am Rails developer”, :”I belongs to the”, :” India”, :text=, :”This is string performance test”]

Conclusion:

In ruby programming language, We should to use Symbol as much as we can instead of String, To optimize performance and save memory.

example:

hash = {“a” => “something”, “b” => “else”}
hash1 = {:a => “something”, :b => “else”}

I hope it will help to understand String and Symbol, shot a comment if i missed any things ūüôā

Passing Blocks in Ruby methods


Today moving around Proc class in Ruby. I come across details about Ruby Blocks and How ruby methods receive block.

There are two way to receive blocks in Ruby methods.

1. Yield

Ruby’s yield statement gives control to a user specified block from the method’s body.

def test
   yield 5,10
   puts "You are in the method test"
   yield 100,200
end

test {|i,j| puts "You are in the block"}

OutPut:

You are in the block
You are in the method test
You are in the block

Even we  can pass parameters with the yield statement.

def test
   yield 5,10
   puts "You are in the method test"
   yield 100,200
end
test {|i,j| puts "You are in the block #{i} and #{j}"}

OutPut:

You are in the block 5 and 10
You are in the method test
You are in the block 100 and 200

2. Proc

If the last argument of a method is preceded by &(Object=Proc.new), then you can pass a block to this method and this block will be assigned to the last parameter. In case both * and & are present in the argument list, & should come later.

The & calls ‘to_proc’ on the object, and passes it as a block to the method.
In Rails, to_proc is implemented on Symbol, so that these two calls are equivalent:
something {|i| i.foo } and  something(&:foo)

def test(b=Proc.new)   
   b.call(10,20)
   puts "You are in the method test"
   yield 100,200
end
OR
def test(&b)
   p b    
   b.call(10,20)
   puts "You are in the method test"
   yield 100,200
end

test {|i,j| puts "You are in the block #{i} and #{j}"}

Output:

You are in the block 10 and 20
You are in the method test
You are in the block 100 and 200

I hope, it will give sense of how ruby methods call blocks and yield. You can get code from my github Passing-Blocks-in-Ruby-methods.

Multiple Inheritance, Ruby



Multiple inheritance is a feature of object-oriented computer programing
languages in which a class can inherit(Inheritance is a relation between two classes)
characteristics and features from more than one superclass.  It is distinct
to single inheritance, where a class may only inherit from one particular superclass.

Ruby doesn't support Multiple inheritance . Ruby has single inheritance(each class has one and only one parent class). Example: All cats are mammals, and all mammals are animals.The benefit of inheritance is that classes lower down the hierarchy get the features of those higher up, but can also add specific features of their own. If all mammals breathe, then all cats breathe. class ClassA puts :A end class ClassB puts :B end # will not work class Inheritor < ClassA, ClassB puts :A puts :B end # To make things work: module ModuleA puts :A end module ModuleB puts :B end # class Inheritor mixin ModuleA,ModuleB modules class Inheritor include ModuleA include ModuleB puts :I end I hope it give small clarification on ruby inheritance features.

Ruby Mixin


Mixin(Any class {or object} can include a Module, In other word a class that is mixed with a module.) is a class that provides a certain functionality to be inherited or just reused(include/require/load/extent) other module.

When to use mixins?

Use mixins whenever you need to share behaviors between different classes.

Let’s talk about a class:

We can split our code in different classes and inherit them into child class. But problem is that, In ruby, A class can’t¬† inherit features from more than one parent class, the class is supposed to show multiple inheritance and Ruby does not suppoprt mutiple inheritance.

Let’s talk about a Module:

Modules in ruby are similar to classes, Modules are a way of grouping together methods, classes, and constants. Modules give us  two major benefits:

1.  Modules provide a namespace and prevent name clashes.

2. Modules implement the mixin facility.

But a module is not really a class. You can’t instantiate a Module, and thus it does not have¬†self.

1.  A module can have no instances.

2.  A modu le can have no subclasses.

Mixin:

Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the module.

Sample code to understand of mixin:

Let’s create two module and one test class.

module A
  def a1
    puts 'I am in method a1'
  end
end

module B
  def b1
    puts 'I am in method B1'
  end
end

class Test
  include A
  include B

  def display
    puts 'Modules are included'
  end
end

object=Test.new
object.display
object.a1
object.b1

Outputs:
Modules are included
I am in method a1
I am in method b1

Hope this helps.