Module: ActiveResource::Attributes::CompatibilityPatch

Defined in:
lib/activeresource-attributes.rb

Instance Method Summary collapse

Instance Method Details

#initialize(attributes = {}, persisted = false) ⇒ Object



11
12
13
14
15
16
# File 'lib/activeresource-attributes.rb', line 11

def initialize(attributes = {}, persisted = false)
  @attributes = self.class._default_attributes.deep_dup
  @prefix_options = {}
  @persisted = persisted
  load(attributes, false, persisted)
end

#load(attributes, remove_root = false, persisted = false) ⇒ Object



18
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
47
48
49
50
51
52
53
54
55
# File 'lib/activeresource-attributes.rb', line 18

def load(attributes, remove_root = false, persisted = false)
  unless attributes.respond_to?(:to_hash)
    raise ArgumentError, "expected attributes to be able to convert to Hash, got #{attributes.inspect}"
  end

  attributes = attributes.to_hash
  @prefix_options, attributes = split_options(attributes)

  if attributes.keys.size == 1
    remove_root = self.class.element_name == attributes.keys.first.to_s
  end

  attributes = Formats.remove_root(attributes) if remove_root

  attributes.each do |key, value|
    attribute_value =
      case value
      when Array
        resource = nil
        value.map do |attrs|
          if attrs.is_a?(Hash)
            resource ||= find_or_create_resource_for_collection(key)
            resource.new(attrs, persisted)
          else
            attrs.duplicable? ? attrs.dup : attrs
          end
        end
      when Hash
        resource = find_or_create_resource_for(key)
        resource.new(value, persisted)
      else
        value.duplicable? ? value.dup : value
      end

    public_send("#{key}=", attribute_value)
  end
  self
end