Skip to content

Instantly share code, notes, and snippets.

@jmervine
Created March 16, 2012 20:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmervine/2052509 to your computer and use it in GitHub Desktop.
Save jmervine/2052509 to your computer and use it in GitHub Desktop.
Ruby: dynamically generated object with accessors
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