Skip to content

Instantly share code, notes, and snippets.

@flov
Created September 5, 2012 07:39
Show Gist options
  • Save flov/3632726 to your computer and use it in GitHub Desktop.
Save flov/3632726 to your computer and use it in GitHub Desktop.
Meta Programming!
class Supplier < ActiveRecord::Base
# delegate name, phone, description and contact if franchise is present
%w( name phone description contact ).each do |attribute|
define_method(attribute.to_sym) do
if self.attributes[attribute].present?
self.attributes[attribute]
elsif franchise.present?
franchise.send(attribute)
else
nil
end
end
end
# now I want a method which says
# delegate_if_franchise(:name)
# delegate_if_franchise(:phone)
# delegate_if_franchise(:description)
# delegate_if_franchise(:contact)
# solved it like that:
def self.delegate_if_franchise(*fields)
fields.each do |field|
define_method(field.to_sym) do
if self.attributes[field.to_s].present?
self.attributes[field.to_s]
elsif franchise.present?
franchise.send(field.to_s)
else
nil
end
end
end
end
delegate_if_franchise :name, :phone, :contact, :description
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment