17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
# File 'lib/projectile/identity_map.rb', line 17
def establish_identity_on(attr_name)
define_method("==") do |other|
return false unless self.is_a?(other.class)
self.send(attr_name) == other.send(attr_name)
end
metaclass.instance_eval do
define_method("merge_or_insert") do |json|
return nil unless json
attribute = self.get_attributes.find {|a| a[:name] == attr_name}
key_path = attribute[:key_path]
identity_key = json.valueForKeyPath(key_path)
return nil unless identity_key
new_model = self.new json
old_model = self.identity_map[identity_key]
if old_model
old_model.merge_with_model(new_model)
else
self.identity_map[identity_key] = new_model
end
(old_model || new_model)
end
end
end
|