Law Of Demeter (Optimizing Queries)

Smelly Code

class 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 Code

class 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

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers