Created
June 29, 2010 21:46
-
-
Save sbellware/457863 to your computer and use it in GitHub Desktop.
Create an anonymous class from a hash
This file contains hidden or 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
def data_transfer_object(options) | |
Class.new do | |
def initialize(options) | |
options.each do |key, value| | |
instance_variable_set("@#{key}", value) | |
end | |
end | |
options.each do |key, value| | |
define_method key do | |
instance_variable_get "@#{key}" | |
end | |
define_method "#{key}=" do | |
instance_variable_set "@#{key}", value | |
end | |
end | |
end.new(options) | |
end | |
d = data_transfer_object :foo => :bar | |
puts d.foo # outputs "bar" | |
puts d.class # outputs anonymous class | |
Message = d.class # the config class is now assigned to "Message" | |
puts d.class # outputs "Config" | |
m = Message.new :blah => :baz # should be able to make an instance from Message | |
puts m.blah # doesn't work. Message members aren't redefined by the 'new' operator | |
puts m.foo # this works, but foo doesn't have a value | |
m.foo = :bar # assign :bar to Message#foo | |
puts m.foo # outputs 'bar' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment