Module: ValueSemantics::InstanceMethods
- Defined in:
- lib/value_semantics.rb
Overview
All the instance methods available on ValueSemantics objects
Instance Method Summary collapse
-
#==(other) ⇒ Boolean
Loose equality.
-
#eql?(other) ⇒ Boolean
Strict equality.
-
#hash ⇒ Object
Unique-ish integer, based on attributes and class of the object.
-
#initialize(given_attrs = {}) ⇒ Object
Creates a value object based on a Hash of attributes.
- #inspect ⇒ Object
-
#to_h ⇒ Hash
All of the attributes.
-
#with(new_attrs) ⇒ Object
Creates a copy of this object, with the given attributes changed (non-destructive update).
Instance Method Details
#==(other) ⇒ Boolean
Loose equality
114 115 116 |
# File 'lib/value_semantics.rb', line 114 def ==(other) (other.is_a?(self.class) || is_a?(other.class)) && other.to_h.eql?(to_h) end |
#eql?(other) ⇒ Boolean
Strict equality
124 125 126 |
# File 'lib/value_semantics.rb', line 124 def eql?(other) other.class.equal?(self.class) && other.to_h.eql?(to_h) end |
#hash ⇒ Object
Unique-ish integer, based on attributes and class of the object
131 132 133 |
# File 'lib/value_semantics.rb', line 131 def hash to_h.hash ^ self.class.hash end |
#initialize(given_attrs = {}) ⇒ Object
Creates a value object based on a Hash of attributes
74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/value_semantics.rb', line 74 def initialize(given_attrs = {}) remaining_attrs = given_attrs.dup self.class.value_semantics.attributes.each do |attr| key, value = attr.determine_from!(remaining_attrs, self.class) instance_variable_set(attr.instance_variable, value) remaining_attrs.delete(key) end unless remaining_attrs.empty? unrecognised = remaining_attrs.keys.map(&:inspect).join(', ') raise UnrecognizedAttributes, "Unrecognized attributes: #{unrecognised}" end end |
#inspect ⇒ Object
135 136 137 138 139 140 141 |
# File 'lib/value_semantics.rb', line 135 def inspect attrs = to_h .map { |key, value| "#{key}=#{value.inspect}" } .join(" ") "#<#{self.class} #{attrs}>" end |
#to_h ⇒ Hash
Returns all of the attributes.
102 103 104 105 106 |
# File 'lib/value_semantics.rb', line 102 def to_h self.class.value_semantics.attributes .map { |attr| [attr.name, public_send(attr.name)] } .to_h end |
#with(new_attrs) ⇒ Object
Creates a copy of this object, with the given attributes changed (non-destructive update)
95 96 97 |
# File 'lib/value_semantics.rb', line 95 def with(new_attrs) self.class.new(to_h.merge(new_attrs)) end |