Module: AsValue::ValueObject::InstanceMethods

Defined in:
lib/as_value/value_object.rb

Instance Method Summary collapse

Instance Method Details

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



33
34
35
# File 'lib/as_value/value_object.rb', line 33

def ==(other)
  hash == other.hash
end

#before_freezeObject



17
18
19
# File 'lib/as_value/value_object.rb', line 17

def before_freeze
  self.class.instance_variable_get(:@before_freeze)
end

#freeze!Object



39
40
41
42
43
44
45
46
47
# File 'lib/as_value/value_object.rb', line 39

def freeze!
  instance_attributes.each do |attribute|
    define_singleton_method("#{attribute}=") do |*|
      fail AsValue::ImmutableObjectError,
           "ValueObjects are immutable -- write methods are unavailable."
    end
  end
  self.freeze
end

#hashObject



29
30
31
# File 'lib/as_value/value_object.rb', line 29

def hash
  to_h.sort.hash
end

#initialize(params = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/as_value/value_object.rb', line 5

def initialize(params = {})
  self.class.send(:attr_accessor, *instance_attributes)

  params.each do |key, value|
    send("#{key}=", value) if instance_attributes.include? key
  end
  
  before_freeze.call(self) unless before_freeze.nil?

  freeze!
end

#instance_attributesObject



21
22
23
# File 'lib/as_value/value_object.rb', line 21

def instance_attributes
  self.class.instance_variable_get(:@instance_attributes)
end

#to_hObject



25
26
27
# File 'lib/as_value/value_object.rb', line 25

def to_h
  Hash[instance_attributes.map { |attribute| [attribute, send(attribute)] }]
end