Method: LazyResource::Mapping#load

Defined in:
lib/lazy_resource/mapping.rb

#load(hash, persisted = true) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/lazy_resource/mapping.rb', line 54

def load(hash, persisted=true)
  hash.fetched = true and return hash if hash.kind_of?(LazyResource::Mapping)
  return if hash.nil?

  self.tap do |resource|
    resource.persisted = persisted
    resource.fetched = false

    if mapped_name = resource.class.mapped_root_node_name(hash)
      other_attributes = hash
      hash = other_attributes.delete(mapped_name)
      self.other_attributes = other_attributes
    end

    hash.each do |name, value|
      attribute = self.class.attributes[name.to_sym]
      next if attribute.nil?

      type = attribute[:type]
      if type.is_a?(::Array)
        if type.first.include?(LazyResource::Mapping)
          resource.send(:"#{name}=", type.first.load(value))
        else
          resource.send(:"#{name}=", value.map { |object| type.first.parse(object) })
        end
      elsif type.include?(LazyResource::Mapping)
        resource.send(:"#{name}=", type.load(value))
      else
        resource.send(:"#{name}=", type.parse(value)) rescue StandardError
      end
    end

    resource.fetched = true
  end
end