Module: Valued::Mutable

Defined in:
lib/valued/mutable.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define(*attrs, &block) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/valued/mutable.rb', line 13

def self.define(*attrs, &block)
  klass =
    Class.new do
      include Valued::Mutable

      attributes(*attrs)
    end
  klass.class_eval(&block) if block_given?
  klass
end

.included(base) ⇒ Object



24
25
26
# File 'lib/valued/mutable.rb', line 24

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#==(other) ⇒ Object



48
49
50
51
52
# File 'lib/valued/mutable.rb', line 48

def ==(other)
  _attributes.all? do |attribute|
    other.respond_to?(attribute) && send(attribute) == other.send(attribute)
  end
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


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

def eql?(other)
  self.class == other.class && self == other
end

#hashObject



58
59
60
# File 'lib/valued/mutable.rb', line 58

def hash
  (_attributes.map { |attribute| send(attribute) } + [self.class]).hash
end

#initialize(attributes = {}) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/valued/mutable.rb', line 28

def initialize(attributes = {})
  _attributes.each do |attribute|
    if attributes.key?(attribute)
      instance_variable_set("@#{attribute}", attributes.fetch(attribute))
    end
  end
end

#inspectObject



72
73
74
75
76
77
78
# File 'lib/valued/mutable.rb', line 72

def inspect
  inspected_attributes =
    _attributes
      .map { |attribute| "#{attribute}=#{send(attribute).inspect}" }
      .join(' ')
  "#<#{self.class} #{inspected_attributes}>"
end

#to_hObject



62
63
64
65
66
# File 'lib/valued/mutable.rb', line 62

def to_h
  _attributes.each_with_object({}) do |attribute, hash|
    hash[attribute] = send(attribute)
  end
end

#to_sObject



68
69
70
# File 'lib/valued/mutable.rb', line 68

def to_s
  inspect
end

#update(new_attributes) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/valued/mutable.rb', line 36

def update(new_attributes)
  self.class.new(
    _attributes.each_with_object({}) do |attribute, result|
      if new_attributes.key?(attribute)
        result[attribute] = new_attributes[attribute]
      else
        result[attribute] = self.send(attribute)
      end
    end
  )
end