19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
# File 'lib/json_resource/model.rb', line 19
def from_json(obj, defaults: {}, root: nil)
return unless json = parse(obj)
json = json_dig(json, *root) if root
attrs = {}
self.attributes.each do |name, options|
if path = attribute_path(name)
value = json_dig(json, *path)
if !value.nil? && type = attribute_type(name)
value = cast_to(type, value, name)
end
attrs[name] = value
end
end
instance = new(defaults.merge(attrs.compact))
self.objects.each do |name, options|
if path = object_path(name) and obj = json_dig(json, *path)
instance.public_send("#{name}=", object_class(name).from_json(obj))
end
end
self.collections.each do |name, options|
collection = if path = collection_path(name) and obj = json_dig(json, *path)
instance.public_send("#{name}=", collection_class(name).collection_from_json(obj))
else
[]
end
end
instance
end
|