Method: ActiveResource::Base#load

Defined in:
lib/active_resource/base.rb

#load(attributes) ⇒ Object

A method to manually load attributes from a hash. Recursively loads collections of resources. This method is called in initialize and create when a Hash of attributes is provided.

Examples

my_attrs = {:name => 'J&J Textiles', :industry => 'Cloth and textiles'}

the_supplier = Supplier.find(:first)
the_supplier.name
# => 'J&M Textiles'
the_supplier.load(my_attrs)
the_supplier.name('J&J Textiles')

# These two calls are the same as Supplier.new(my_attrs)
my_supplier = Supplier.new
my_supplier.load(my_attrs)

# These three calls are the same as Supplier.create(my_attrs)
your_supplier = Supplier.new
your_supplier.load(my_attrs)
your_supplier.save

Raises:

  • (ArgumentError)


763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/active_resource/base.rb', line 763

def load(attributes)
  raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
  @prefix_options, attributes = split_options(attributes)
  attributes.each do |key, value|
    @attributes[key.to_s] =
      case value
        when Array
          resource = find_or_create_resource_for_collection(key)
          value.map { |attrs| resource.new(attrs) }
        when Hash
          resource = find_or_create_resource_for(key)
          resource.new(value)
        else
          value.dup rescue value
      end
  end
  self
end