Sha256: c6c53ce1dae85ccf59b071d8faf6143f1fe874d36d8614e546be21c46e8ef652
Contents?: true
Size: 1.37 KB
Versions: 1
Compression:
Stored size: 1.37 KB
Contents
class Value def self.new(*fields) return Class.new do attr_reader *fields define_method(:initialize) do |*input_fields| raise ArgumentError.new("wrong number of arguments, #{input_fields.size} for #{fields.size}") if fields.size != input_fields.size fields.each_with_index do |field, index| instance_variable_set('@' + field.to_s, input_fields[index]) end self.freeze end const_set :VALUE_ATTRS, fields def self.with(hash) args = [] self::VALUE_ATTRS.each do |field| val = hash[field] if val args << val else raise ArgumentError.new("Missing field: #{field}") end end unexpected_keys = hash.keys - self::VALUE_ATTRS if unexpected_keys.any? raise ArgumentError.new("Unexpected hash keys: #{unexpected_keys}") end self.new(*args) end def ==(other) self.eql?(other) end def eql?(other) return false if other.class != self.class self.class::VALUE_ATTRS.all? do |field| self.send(field) == other.send(field) end end def hash result = 0 self.class::VALUE_ATTRS.each do |field| result += self.send(field).hash end return result + self.class.hash end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
values-1.3.0 | lib/values.rb |