Class: ValueObject::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/value_object.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Base

Returns a new instance of Base.



20
21
22
23
24
25
26
# File 'lib/value_object.rb', line 20

def initialize(*args)
  if args.length == 1 && args[0].is_a?(Hash)
    fields.each { |f| instance_variable_set "@#{f}", args[0][f] }
  else
    fields.each_with_index { |f, idx| instance_variable_set "@#{f}", args[idx] }
  end
end

Class Method Details

.has_fields(*args) ⇒ Object



10
11
12
13
# File 'lib/value_object.rb', line 10

def has_fields(*args)
  attr_reader *args
  self.fields += args
end

Instance Method Details

#==(other) ⇒ Object



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

def ==(other)
  eql?(other)
end

#copy_with(attrs) ⇒ Object



47
48
49
50
# File 'lib/value_object.rb', line 47

def copy_with(attrs)
  new_attrs = self.to_hash.update(attrs)
  self.class.new(new_attrs)
end

#empty?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/value_object.rb', line 37

def empty?
  fields.all? { |f| send(f).nil? }
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


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

def eql?(other)
  return false if self.class != other.class
  fields.all? { |f| send(f) == other.send(f) }
end

#fieldsObject



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

def fields
  self.class.fields
end

#hashObject

if the class is the same, and the fields’ values are the same, the hash should be the same



54
55
56
# File 'lib/value_object.rb', line 54

def hash
  to_hash.hash + self.class.hash
end

#to_hashObject



41
42
43
44
45
# File 'lib/value_object.rb', line 41

def to_hash
  hash = {}
  fields.each { |f| hash[f] = send(f) }
  hash
end