Skip to content

Instantly share code, notes, and snippets.

@coalwater
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coalwater/3584ed4bf2a15a88c3ee to your computer and use it in GitHub Desktop.
Save coalwater/3584ed4bf2a15a88c3ee to your computer and use it in GitHub Desktop.
law of demeter and rails delegation
class Order < ActiveRecord::Base
delegate :name, :price, to: :item, prefix: true, allow_nil: true
delegate :number, to: :invoice, prefix: true, allow_nil: true
end
class Order < ActiveRecord::Base
delegate :name, :price, to: :item, prefix: true
delegate :number, to: :invoice, prefix: true
end
<%= @order.item_name %>
<%= @order.item_price %>
<%= @order.invoice_number %>
class Order < ActiveRecord::Base
delegate :item_name, :item_price, to: :item
delegate :invoice_number, to: :invoice
end
class Item < ActiveRecord::Base
def item_name
name
end
def item_price
price
end
end
user.address_street_name
recipe.igredient_name
car.horse_power
user.address.street_name
recipe.igredient.name
car.engine.horse_power
class Order < ActiveRecord::Base
def item_name
item.name
end
def item_price
item.price
end
def invoice_number
invoice.number
end
end
<%= @order.item.name %>
<%= @order.item.price %>
<%= @order.invoice.number %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment