Module: ValueSemantics::InstanceMethods

Defined in:
lib/value_semantics.rb

Overview

All the instance methods available on ValueSemantics objects

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Boolean

Loose equality

Returns:

  • (Boolean)

    whether all attributes are equal, and the object classes are ancestors of eachother in any way



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

Returns:

  • (Boolean)

    whether all attribuets are equal, and both objects has the exact same class



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

#hashObject

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

Parameters:

  • given_attrs (Hash) (defaults to: {})

    a hash of attributes, with symbols for keys

Raises:

  • (UnrecognizedAttributes)

    if given_attrs contains keys that are not attributes

  • (MissingAttributes)

    if given_attrs is missing any attributes that do not have defaults

  • (ArgumentError)

    if any attribute values do no pass their validators



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

#inspectObject



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_hHash

Returns all of the attributes.

Returns:

  • (Hash)

    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)

Parameters:

  • new_attrs (Hash)

    the attributes to change

Returns:

  • A new object, with the attribute changes applied



95
96
97
# File 'lib/value_semantics.rb', line 95

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