/ ruby

Lessons learnt and Good Practices

There are several practices followed in Rails.

Since ruby is the backbone of rails, here are few practices that are recommended:

Lets consider a class ABC:

class Animal
  attr_accessor :id, :type
  def self.mouse(object, a1, a2)
     puts "#{self}"
  def animal
    puts "I m in animal instance method"
    yield if block_given?
  def id
  def initialize(id, type)
    @id = id
    @type = type
  def update_extra_attrs(a1, a2)
     puts "#{self.inspect}"

Execution & Explanation:

  1. To change the behaviour of attribute's value, always make use of ruby's getter and setter methods.
animal = Animal.new('1', 'Mouse')
puts animal.inspect # #
puts animal.id.class # Fixnum

As per this scenario, Ruby is object-oriented so every attribute of a class is a method itself. When an animal object is created with id as '1', it might require that id should be read as integer, so make use of id method itself to override its behaviour.

  1. Avoid to construct class method when the method actually requires instance of the class.
animal = Animal.new('1', 'Mouse') # #
Animal.mouse(animal, 'dummy', 'args') # Animal

As per above scenario class method 'mouse' accepts 3 arguments including instance of its own class. Rather than constructing class method with an instance passed as args, we can make use of instance method and prevent extra arguments. This will not only depicts convention over configuration but also enhance ruby execution.

So by refactoring above pseuso-code, here we can make a small change by utilising instance method ('update_extra_attrs') instead of class method ('mouse'):

animal = Animal.new('1', 'Mouse') # #
animal.update_extra_attrs('dummy', 'args') # #

Here, via instance method, we dont need to pass separate argument i.e animal to get class object.

  1. In Rails, we tend to keep or code dry. What if there is some shared code and we want to add some more logic to it and execute all them ?
animal = Animal.new('1', 'Mouse')
animal.animal do
  puts "add more property"

animal.animal do
  puts "add more behaviour"

------ Results:
I m in animal instance method
add more property
I m in animal instance method
add more behaviour

In Ruby, we can provide extra block of code while calling a method. Here, we have 'animal' instance method which is a shared code. But we want to have some other logic as per requirement, we can pass the block when calling a method. If we look into 'animal' method, it calls up 'yield'. 'yield' executes the extra block provide along with method when called.

There are many references that elaborates ruby's object oriented styles.