Module: Valuables::Entity

Defined in:
lib/valuables/entity.rb

Overview

Include Entity to make a class an immutable value object.

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#hashObject (readonly)

:nodoc:



32
33
34
# File 'lib/valuables/entity.rb', line 32

def hash
  @hash
end

Class Method Details

.included(cls) ⇒ Object

:nodoc:



7
8
9
# File 'lib/valuables/entity.rb', line 7

def self.included(cls) # :nodoc:
  cls.extend ClassMethods
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

Comparse two objects

Two entities are considered equal if they are instances of the same class and their internal attributes are equal.



55
56
57
58
# File 'lib/valuables/entity.rb', line 55

def ==(other)
  self.class == other.class &&
    attributes == other.attributes
end

#initialize(**kwargs) ⇒ Object

Initialize a new entity

Provide the entity’s attributes as key/value pairs in kwargs. Any attributes you provide will be duplicated and frozen, so you need not worry about later modifications to any values passed in.



43
44
45
46
47
48
49
# File 'lib/valuables/entity.rb', line 43

def initialize(**kwargs)
  assert_required_attributes(kwargs)
  assert_no_extra_attributes(kwargs)
  @attributes = Valuables::DeepFreeze.deep_freeze(kwargs)
  @hash = self.class.hash ^ @attributes.hash
  freeze
end

#inspectObject

:nodoc:



66
67
68
# File 'lib/valuables/entity.rb', line 66

def inspect # :nodoc:
  "#<#{self.class} #{attributes.map { |k, v| "#{k}: #{v.inspect}" }.join(' ')}>"
end

#to_hObject

Get a Hash representation of this entity.



62
63
64
# File 'lib/valuables/entity.rb', line 62

def to_h
  @attributes
end