Created
May 3, 2013 14:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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