Posts

Showing posts from April, 2015

Law Of Demeter (Optimizing Queries)

Smelly Codeclass Student < ActiveRecord::Base belongs_to :school end <%= @student.school.name %> <%= @student.school.address %> <%= @student.school.phone %> In the above code, Student model calls the properties of the association(User). The properties of the school being name, address and phone. This defies the Law Of Demeter.

Refactored Codeclass Student < ActiveRecord::Base belongs_to :school delegate :name, :address, :phone, :to => :school, :prefix => true end <%= @student.school_name %> <%= @student.school_address %> <%= @student.school_phone %> Rails comes to your rescue as it provides a helper method delegate which uses the DSL way to generate the wrapper methods. Also, it prevents the error call method on nil object if you add option :allow_nil => true