Created
July 30, 2011 02:14
-
-
Save foca/1115114 to your computer and use it in GitHub Desktop.
Extremely lightweight "Struct" that only defines attribute readers
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
module ValueObject | |
def self.new(*attrs) | |
klass = Class.new(Object) | |
klass.send(:attr_reader, *attrs) | |
klass.send(:define_method, :initialize) do |*args| | |
raise ArgumentError, "wrong number of arguments (#{args.size} for #{attrs.size})" unless args.size == attrs.size | |
attrs.each_with_index do |attr, idx| | |
instance_variable_set("@#{attr}", args[idx]) | |
end | |
end | |
klass | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use case: