Created
March 16, 2012 20:37
-
-
Save jmervine/2052509 to your computer and use it in GitHub Desktop.
Ruby: dynamically generated object with accessors
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
class Item | |
def initialize item | |
raise "expected Hash param" unless item.kind_of? Hash | |
item.each do |key,value| | |
instance_variable_set(clean_key(key), value) | |
define_singleton_method(key.to_s) { instance_variable_get( clean_key(key) ) } | |
define_singleton_method("#{key.to_s}=") { |val| instance_variable_set( clean_key(key), val ) } | |
end | |
end | |
protected | |
# ensure all keys are clean keys, was more necessary when using | |
# using missing method, but keeping it to be safe | |
def clean_key key | |
"@#{key.to_s.gsub(/^\@/, "").gsub(/=$/, "")}".to_sym | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment