Skip to content

Instantly share code, notes, and snippets.

@foca
Created July 30, 2011 02:14
Show Gist options
  • Save foca/1115114 to your computer and use it in GitHub Desktop.
Save foca/1115114 to your computer and use it in GitHub Desktop.
Extremely lightweight "Struct" that only defines attribute readers
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
@guillermo
Copy link

Use case:

class Name < ValueObject.new(:name, :surname)
   def to_s
     [name,surname].compact.join(" ")
   end
end

n = Name.new("Guillermo", "Alvarez")
n.name    #=> "Guillermo"
n.surname #=> "Alvarez"
n.to_s    #=> "Guillermo Álvarez"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment