Module: JsonResource::Model::ClassMethods

Defined in:
lib/json_resource/model.rb

Instance Method Summary collapse

Instance Method Details

#basenameObject



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

def basename
  name.sub(/^.*::/, '')
end

#collection_from_json(obj, defaults: {}, root: nil) ⇒ Object



48
49
50
51
52
# File 'lib/json_resource/model.rb', line 48

def collection_from_json(obj, defaults: {}, root: nil)
  json = parse(obj)
  json = json_dig(json, *root) if root
  json.map { |hsh| from_json(hsh, defaults: defaults) }.compact
end

#from_json(obj, defaults: {}, root: nil) ⇒ Object



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