Skip to content

Instantly share code, notes, and snippets.

@adambird
Created May 3, 2013 14:53
Show Gist options
  • Save adambird/5509602 to your computer and use it in GitHub Desktop.
Save adambird/5509602 to your computer and use it in GitHub Desktop.
Example class method to generate boiler plate methods for a complex attribute of an object. Primary use case is for use by a web form.
module ClassMethods
def address_attribute(name)
define_method(name) { instance_variable_get("@#{name}") }
define_method("#{name}=") { |value| instance_variable_set("@#{name}", value) }
define_method("_get_init_#{name}") { instance_variable_get("@#{name}") || instance_variable_set("@#{name}", BunchCore::Address.new) }
[:street_one, :street_two, :town, :county, :country, :post_code].each do |m|
define_method("#{name}_#{m}") { send(name) ? send(name).send(m) : nil }
define_method("#{name}_#{m}=") { |value| send("_get_init_#{name}").send("#{m}=", value) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment