Module: ValueSemantics::Semantics

Defined in:
lib/value_semantics.rb

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Object



56
57
58
# File 'lib/value_semantics.rb', line 56

def ==(other)
  (other.is_a?(self.class) || is_a?(other.class)) && other.to_h == to_h
end

#eql?(other) ⇒ Boolean



60
61
62
# File 'lib/value_semantics.rb', line 60

def eql?(other)
  other.class.equal?(self.class) && other.to_h.eql?(to_h)
end

#hash ⇒ Object



64
65
66
# File 'lib/value_semantics.rb', line 64

def hash
  @__hash ||= (to_h.hash ^ self.class.hash)
end

#initialize(given_attrs = {}) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/value_semantics.rb', line 31

def initialize(given_attrs = {})
  remaining_attrs = given_attrs.dup

  self.class.attributes.each do |attr|
    key, value = attr.determine_from!(remaining_attrs, self)
    instance_variable_set(attr.instance_variable, value)
    remaining_attrs.delete(key)
  end

  unless remaining_attrs.empty?
    unrecognised = remaining_attrs.keys.map(&:inspect).join(', ')
    raise ArgumentError, "Unrecognised attributes: #{unrecognised}"
  end
end

#inspect ⇒ Object



68
69
70
71
72
73
74
# File 'lib/value_semantics.rb', line 68

def inspect
  attrs = to_h
    .map { |key, value| "#{key}=#{value.inspect}" }
    .join(" ")

  "#<#{self.class} #{attrs}>"
end

#to_h ⇒ Object



50
51
52
53
54
# File 'lib/value_semantics.rb', line 50

def to_h
  self.class.attributes
    .map { |attr| [attr.name, public_send(attr.name)] }
    .to_h
end

#with(new_attrs) ⇒ Object



46
47
48
# File 'lib/value_semantics.rb', line 46

def with(new_attrs)
  self.class.new(to_h.merge(new_attrs))
end