Module: Lutaml::Model::ComparableModel
- Included in:
- Serialize
- Defined in:
- lib/lutaml/model/comparable_model.rb
Overview
ComparableModel module provides functionality to compare and diff two objects of the same class, based on their attribute values.
Defined Under Namespace
Modules: ClassMethods
Classes: DiffContext, Tree
Class Method Summary
collapse
Instance Method Summary
collapse
Class Method Details
.included(base) ⇒ Object
8
9
10
|
# File 'lib/lutaml/model/comparable_model.rb', line 8
def self.included(base)
base.extend(ClassMethods)
end
|
Instance Method Details
#already_compared?(other, compared_objects) ⇒ Boolean
43
44
45
|
# File 'lib/lutaml/model/comparable_model.rb', line 43
def already_compared?(other, compared_objects)
compared_objects[comparison_key(other)]
end
|
#attributes_hash(processed_objects) ⇒ Object
60
61
62
63
64
65
66
67
68
69
70
|
# File 'lib/lutaml/model/comparable_model.rb', line 60
def attributes_hash(processed_objects)
self.class.attributes.map do |attr, _|
attr_value = send(attr)
if attr_value.respond_to?(:calculate_hash)
attr_value.calculate_hash(processed_objects)
else
attr_value.hash
end
end
end
|
#calculate_hash(processed_objects = {}.compare_by_identity) ⇒ Object
53
54
55
56
57
58
|
# File 'lib/lutaml/model/comparable_model.rb', line 53
def calculate_hash(processed_objects = {}.compare_by_identity)
return if processed_objects.key?(self)
processed_objects[self] = true
([self.class] + attributes_hash(processed_objects)).hash
end
|
#comparison_key(other) ⇒ Object
39
40
41
|
# File 'lib/lutaml/model/comparable_model.rb', line 39
def comparison_key(other)
"#{object_id}:#{other.object_id}"
end
|
#eql?(other, compared_objects = {}) ⇒ Boolean
Also known as:
==
Checks if two objects are equal based on their attributes
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
# File 'lib/lutaml/model/comparable_model.rb', line 15
def eql?(other, compared_objects = {})
return true if equal?(other)
return false unless same_class?(other)
return true if already_compared?(other, compared_objects)
compared_objects[comparison_key(other)] = true
self.class.attributes.all? do |attr, _|
attr_value = send(attr)
other_value = other.send(attr)
if attr_value.respond_to?(:eql?) && same_class?(attr_value)
attr_value.eql?(other_value, compared_objects)
else
attr_value == other_value
end
end
end
|
#hash ⇒ Integer
Generates a hash value for the object
49
50
51
|
# File 'lib/lutaml/model/comparable_model.rb', line 49
def hash
calculate_hash
end
|
#same_class?(other) ⇒ Boolean
35
36
37
|
# File 'lib/lutaml/model/comparable_model.rb', line 35
def same_class?(other)
other.instance_of?(self.class)
end
|