Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fast_value_object.rb
module ValueObject
def self.included(klass)
klass.extend(ClassMethods)
klass.attributes # Force instantiation
end
def initialize(data)
data.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def ==(other)
equality_key == other.equality_key
end
def eql?(other)
equality_key.eql?(other.equality_key)
end
def hash
equality_key.hash
end
def equality_key
self.class.attributes.map {|key, _|
send(key)
}
end
def inspect
keyvalues = self.class.attributes.map {|key, _|
"#{key}=#{send(key).inspect}"
}.join(" ")
"<#{self.class.name} #{keyvalues}>"
end
def to_s
inspect
end
module ClassMethods
def values(&block)
instance_eval(&block)
end
def attributes
@attributes ||= {}
end
def attribute(name, type = Object)
attributes[name] = type
define_method(name) do
instance_variable_get("@#{name}")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.