Rails. Source: www.usapics.net

Design Patterns: Law of Demeter with Rails

Developing better Rails applications

@employee.company.name
@employee.company.location.street

Use only one dot.

@employee.company_name
@employee.company_street
class Employee < ActiveRecord::Base
belongs_to :company
end
class Company < ActiveRecord::Base
has_one :location
has_many :employees
end
class Location < ActiveRecord::Base
belongs_to :company
end

Simply say, delegation allows you to use methods of one object from another.

# instead of @employee.company.name method 
<%= @employee.company_name %>
class Employee < ActiveRecord::Base
belongs_to :company
delegate :name, to: :company, prefix: 'company'
end
class Employee < ActiveRecord::Base
belongs_to :company
delegate :name, :phone, to: :company, prefix: 'company'
end
<%= @employee.company_name %>
<%= @employee.company_phone %>
class Company < ActiveRecord::Base
has_one :location
has_many :employees
delegate :city, :street, to: :location
end
class Employee < ActiveRecord::Base
belongs_to :company
delegate :name, :city, :street, to: :company, prefix: 'company'
end
<%= @employee.company_name %>,
<%= @employee.company_city %>,
<%= @employee.company_street %>
@employee.cmpn_name
class Location < ActiveRecord::Base
belongs_to :company
def street
str
end
# or alias method
# alias_method :street, :str
end
delegate ..., allow_nil: true

--

--

Web-developer, entrepreneur, researcher

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store