| Class | ActiveResource::Base |
| In: |
vendor/rails/activeresource/lib/active_resource/base.rb
|
| Parent: | Object |
ActiveResource::Base is the main class for mapping RESTful resources as models in a Rails application.
For an outline of what Active Resource is capable of, see files/vendor/rails/activeresource/README.html.
Active Resource objects represent your RESTful resources as manipulatable Ruby objects. To map resources to Ruby objects, Active Resource only needs a class name that corresponds to the resource name (e.g., the class Person maps to the resources people, very similarly to Active Record) and a site value, which holds the URI of the resources.
class Person < ActiveResource::Base
self.site = "http://api.people.com:3000/"
end
Now the Person class is mapped to RESTful resources located at api.people.com:3000/people/, and you can now use Active Resource‘s lifecycles methods to manipulate resources. In the case where you already have an existing model with the same name as the desired RESTful resource you can set the element_name value.
class PersonResource < ActiveResource::Base
self.site = "http://api.people.com:3000/"
self.element_name = "person"
end
Active Resource exposes methods for creating, finding, updating, and deleting resources from REST web services.
ryan = Person.new(:first => 'Ryan', :last => 'Daigle') ryan.save # => true ryan.id # => 2 Person.exists?(ryan.id) # => true ryan.exists? # => true ryan = Person.find(1) # Resource holding our newly created Person object ryan.first = 'Rizzle' ryan.save # => true ryan.destroy # => true
As you can see, these are very similar to Active Record‘s lifecycle methods for database records. You can read more about each of these methods in their respective documentation.
Since simple CRUD/lifecycle methods can‘t accomplish every task, Active Resource also supports defining your own custom REST methods. To invoke them, Active Resource provides the get, post, put and \delete methods where you can specify a custom REST method name to invoke.
# POST to the custom 'register' REST method, i.e. POST /people/new/register.xml.
Person.new(:name => 'Ryan').post(:register)
# => { :id => 1, :name => 'Ryan', :position => 'Clerk' }
# PUT an update by invoking the 'promote' REST method, i.e. PUT /people/1/promote.xml?position=Manager.
Person.find(1).put(:promote, :position => 'Manager')
# => { :id => 1, :name => 'Ryan', :position => 'Manager' }
# GET all the positions available, i.e. GET /people/positions.xml.
Person.get(:positions)
# => [{:name => 'Manager'}, {:name => 'Clerk'}]
# DELETE to 'fire' a person, i.e. DELETE /people/1/fire.xml.
Person.find(1).delete(:fire)
For more information on using custom REST methods, see the ActiveResource::CustomMethods documentation.
You can validate resources client side by overriding validation methods in the base class.
class Person < ActiveResource::Base
self.site = "http://api.people.com:3000/"
protected
def validate
errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/
end
end
See the ActiveResource::Validations documentation for more information.
Many REST APIs will require authentication, usually in the form of basic HTTP authentication. Authentication can be specified by:
class Person < ActiveResource::Base self.site = "http://ryan:password@api.people.com:3000/" end
class Person < ActiveResource::Base self.site = "http://api.people.com:3000/" self.user = "ryan" self.password = "password" end
For obvious security reasons, it is probably best if such services are available over HTTPS.
Note: Some values cannot be provided in the URL passed to site. e.g. email addresses as usernames. In those situations you should use the separate user and password option.
class Person < ActiveResource::Base
self.site = "https://secure.api.people.com/"
self.ssl_options = {:cert => OpenSSL::X509::Certificate.new(File.open(pem_file))
:key => OpenSSL::PKey::RSA.new(File.open(pem_file)),
:ca_path => "/path/to/OpenSSL/formatted/CA_Certs",
:verify_mode => OpenSSL::SSL::VERIFY_PEER}
end
Error handling and validation is handled in much the same manner as you‘re used to seeing in Active Record. Both the response code in the HTTP response and the body of the response are used to indicate that an error occurred.
When a GET is requested for a resource that does not exist, the HTTP 404 (Resource Not Found) response code will be returned from the server which will raise an ActiveResource::ResourceNotFound exception.
# GET http://api.people.com:3000/people/999.xml ryan = Person.find(999) # 404, raises ActiveResource::ResourceNotFound
404 is just one of the HTTP error response codes that Active Resource will handle with its own exception. The following HTTP response codes will also result in these exceptions:
These custom exceptions allow you to deal with resource errors more naturally and with more precision rather than returning a general HTTP error. For example:
begin
ryan = Person.find(my_id)
rescue ActiveResource::ResourceNotFound
redirect_to :action => 'not_found'
rescue ActiveResource::ResourceConflict, ActiveResource::ResourceInvalid
redirect_to :action => 'new'
end
Active Resource supports validations on resources and will return errors if any these validations fail (e.g., "First name can not be blank" and so on). These types of errors are denoted in the response by a response code of 422 and an XML or JSON representation of the validation errors. The save operation will then fail (with a false return value) and the validation errors can be accessed on the resource in question.
ryan = Person.find(1)
ryan.first # => ''
ryan.save # => false
# When
# PUT http://api.people.com:3000/people/1.xml
# or
# PUT http://api.people.com:3000/people/1.json
# is requested with invalid values, the response is:
#
# Response (422):
# <errors type="array"><error>First cannot be empty</error></errors>
# or
# {"errors":["First cannot be empty"]}
#
ryan.errors.invalid?(:first) # => true
ryan.errors.full_messages # => ['First cannot be empty']
Learn more about Active Resource‘s validation features in the ActiveResource::Validations documentation.
Active Resource relies on HTTP to access RESTful APIs and as such is inherently susceptible to slow or unresponsive servers. In such cases, your Active Resource method calls could \timeout. You can control the amount of time before Active Resource times out with the timeout variable.
class Person < ActiveResource::Base
self.site = "http://api.people.com:3000/"
self.timeout = 5
end
This sets the timeout to 5 seconds. You can adjust the timeout to a value suitable for the RESTful API you are accessing. It is recommended to set this to a reasonably low value to allow your Active Resource clients (especially if you are using Active Resource in a Rails application) to fail-fast (see en.wikipedia.org/wiki/Fail-fast) rather than cause cascading failures that could incapacitate your server.
When a \timeout occurs, an ActiveResource::TimeoutError is raised. You should rescue from ActiveResource::TimeoutError in your Active Resource method calls.
Internally, Active Resource relies on Ruby‘s Net::HTTP library to make HTTP requests. Setting timeout sets the read_timeout of the internal Net::HTTP instance to the same value. The default read_timeout is 60 seconds on most Ruby implementations.
| prefix= | -> | set_prefix |
| element_name= | -> | set_element_name |
| collection_name= | -> | set_collection_name |
| primary_key= | -> | set_primary_key |
| respond_to? | -> | respond_to_without_attributes? |
| For checking respond_to? without searching the attributes (which is faster). | ||
Gets the collection path for the REST resources. If the query_options parameter is omitted, Rails will split from the prefix_options.
Post.collection_path
# => /posts.xml
Comment.collection_path(:post_id => 5)
# => /posts/5/comments.xml
Comment.collection_path(:post_id => 5, :active => 1)
# => /posts/5/comments.xml?active=1
Comment.collection_path({:post_id => 5}, {:active => 1})
# => /posts/5/comments.xml?active=1
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 497
497: def collection_path(prefix_options = {}, query_options = nil)
498: prefix_options, query_options = split_options(prefix_options) if query_options.nil?
499: "#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}"
500: end
An instance of ActiveResource::Connection that is the base \connection to the remote service. The refresh parameter toggles whether or not the \connection is refreshed at every request or not (defaults to false).
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 382
382: def connection(refresh = false)
383: if defined?(@connection) || superclass == Object
384: @connection = Connection.new(site, format) if refresh || @connection.nil?
385: @connection.proxy = proxy if proxy
386: @connection.user = user if user
387: @connection.password = password if password
388: @connection.timeout = timeout if timeout
389: @connection.ssl_options = ssl_options if ssl_options
390: @connection
391: else
392: superclass.connection
393: end
394: end
Creates a new resource instance and makes a request to the remote service that it be saved, making it equivalent to the following simultaneous calls:
ryan = Person.new(:first => 'ryan') ryan.save
Returns the newly created resource. If a failure has occurred an exception will be raised (see save). If the resource is invalid and has not been saved then valid? will return false, while new? will still return true.
Person.create(:name => 'Jeremy', :email => 'myname@nospam.com', :enabled => true) my_person = Person.find(:first) my_person.email # => myname@nospam.com dhh = Person.create(:name => 'David', :email => 'dhh@nospam.com', :enabled => true) dhh.valid? # => true dhh.new? # => false # We'll assume that there's a validation that requires the name attribute that_guy = Person.create(:name => '', :email => 'thatguy@nospam.com', :enabled => true) that_guy.valid? # => false that_guy.new? # => true
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 528
528: def create(attributes = {})
529: self.new(attributes).tap { |resource| resource.save }
530: end
Deletes the resources with the ID in the id parameter.
All options specify \prefix and query parameters.
Event.delete(2) # sends DELETE /events/2 Event.create(:name => 'Free Concert', :location => 'Community Center') my_event = Event.find(:first) # let's assume this is event with ID 7 Event.delete(my_event.id) # sends DELETE /events/7 # Let's assume a request to events/5/cancel.xml Event.delete(params[:id]) # sends DELETE /events/5
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 605
605: def delete(id, options = {})
606: connection.delete(element_path(id, options))
607: end
Gets the element path for the given ID in id. If the query_options parameter is omitted, Rails will split from the \prefix options.
prefix_options - A \hash to add a \prefix to the request for nested URLs (e.g., :account_id => 19
would yield a URL like <tt>/accounts/19/purchases.xml</tt>).
query_options - A \hash to add items to the query string for the request.
Post.element_path(1)
# => /posts/1.xml
Comment.element_path(1, :post_id => 5)
# => /posts/5/comments/1.xml
Comment.element_path(1, :post_id => 5, :active => 1)
# => /posts/5/comments/1.xml?active=1
Comment.element_path(1, {:post_id => 5}, {:active => 1})
# => /posts/5/comments/1.xml?active=1
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 471
471: def element_path(id, prefix_options = {}, query_options = nil)
472: prefix_options, query_options = split_options(prefix_options) if query_options.nil?
473: "#{prefix(prefix_options)}#{collection_name}/#{id}.#{format.extension}#{query_string(query_options)}"
474: end
Asserts the existence of a resource, returning true if the resource is found.
Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...') Note.exists?(1) # => true Note.exists(1349) # => false
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 616
616: def exists?(id, options = {})
617: if id
618: prefix_options, query_options = split_options(options[:params])
619: path = element_path(id, prefix_options, query_options)
620: response = connection.head(path, headers)
621: response.code.to_i == 200
622: end
623: # id && !find_single(id, options).nil?
624: rescue ActiveResource::ResourceNotFound, ActiveResource::ResourceGone
625: false
626: end
Core method for finding resources. Used similarly to Active Record‘s find method.
The first argument is considered to be the scope of the query. That is, how many resources are returned from the request. It can be one of the following.
Person.find(1)
# => GET /people/1.xml
Person.find(:all)
# => GET /people.xml
Person.find(:all, :params => { :title => "CEO" })
# => GET /people.xml?title=CEO
Person.find(:first, :from => :managers)
# => GET /people/managers.xml
Person.find(:last, :from => :managers)
# => GET /people/managers.xml
Person.find(:all, :from => "/companies/1/people.xml")
# => GET /companies/1/people.xml
Person.find(:one, :from => :leader)
# => GET /people/leader.xml
Person.find(:all, :from => :developers, :params => { :language => 'ruby' })
# => GET /people/developers.xml?language=ruby
Person.find(:one, :from => "/companies/1/manager.xml")
# => GET /companies/1/manager.xml
StreetAddress.find(1, :params => { :person_id => 1 })
# => GET /people/1/street_addresses/1.xml
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 578
578: def find(*arguments)
579: scope = arguments.slice!(0)
580: options = arguments.slice!(0) || {}
581:
582: case scope
583: when :all then find_every(options)
584: when :first then find_every(options).first
585: when :last then find_every(options).last
586: when :one then find_one(options)
587: else find_single(scope, options)
588: end
589: end
Returns the current format, default is ActiveResource::Formats::XmlFormat.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 335
335: def format
336: read_inheritable_attribute(:format) || ActiveResource::Formats[:xml]
337: end
Sets the format that attributes are sent and received in from a mime type reference:
Person.format = :json Person.find(1) # => GET /people/1.json Person.format = ActiveResource::Formats::XmlFormat Person.find(1) # => GET /people/1.xml
Default format is :xml.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 326
326: def format=(mime_type_reference_or_format)
327: format = mime_type_reference_or_format.is_a?(Symbol) ?
328: ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format
329:
330: write_inheritable_attribute(:format, format)
331: connection.format = format if site
332: end
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 396
396: def headers
397: @headers ||= {}
398: end
Constructor method for \new resources; the optional attributes parameter takes a \hash of attributes for the \new resource.
my_course = Course.new my_course.name = "Western Civilization" my_course.lecturer = "Don Trotter" my_course.save my_other_course = Course.new(:name => "Philosophy: Reason and Being", :lecturer => "Ralph Cling") my_other_course.save
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 721
721: def initialize(attributes = {})
722: @attributes = {}
723: @prefix_options = {}
724: load(attributes)
725: end
Gets the \password for REST HTTP authentication.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 302
302: def password
303: # Not using superclass_delegating_reader. See +site+ for explanation
304: if defined?(@password)
305: @password
306: elsif superclass != Object && superclass.password
307: superclass.password.dup.freeze
308: end
309: end
Gets the \prefix for a resource‘s nested URL (e.g., prefix/collectionname/1.xml) This method is regenerated at runtime based on what the \prefix is set to.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 409
409: def prefix(options={})
410: default = site.path
411: default << '/' unless default[-1..-1] == '/'
412: # generate the actual method based on the current site path
413: self.prefix = default
414: prefix(options)
415: end
Sets the \prefix for a resource‘s nested URL (e.g., prefix/collectionname/1.xml). Default value is site.path.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 426
426: def prefix=(value = '/')
427: # Replace :placeholders with '#{embedded options[:lookups]}'
428: prefix_call = value.gsub(/:\w+/) { |key| "\#{options[#{key}]}" }
429:
430: # Clear prefix parameters in case they have been cached
431: @prefix_parameters = nil
432:
433: # Redefine the new methods.
434: code = "def prefix_source() \"\#{value}\" end\ndef prefix(options={}) \"\#{prefix_call}\" end\n"
435: silence_warnings { instance_eval code, __FILE__, __LINE__ }
436: rescue
437: logger.error "Couldn't set prefix: #{$!}\n #{code}"
438: raise
439: end
An attribute reader for the source string for the resource path \prefix. This method is regenerated at runtime based on what the \prefix is set to.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 419
419: def prefix_source
420: prefix # generate #prefix and #prefix_source methods first
421: prefix_source
422: end
Gets the \proxy variable if a proxy is required
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 270
270: def proxy
271: # Not using superclass_delegating_reader. See +site+ for explanation
272: if defined?(@proxy)
273: @proxy
274: elsif superclass != Object && superclass.proxy
275: superclass.proxy.dup.freeze
276: end
277: end
Gets the URI of the REST resources to map for this class. The site variable is required for Active Resource‘s mapping to work.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 233
233: def site
234: # Not using superclass_delegating_reader because don't want subclasses to modify superclass instance
235: #
236: # With superclass_delegating_reader
237: #
238: # Parent.site = 'http://anonymous@test.com'
239: # Subclass.site # => 'http://anonymous@test.com'
240: # Subclass.site.user = 'david'
241: # Parent.site # => 'http://david@test.com'
242: #
243: # Without superclass_delegating_reader (expected behaviour)
244: #
245: # Parent.site = 'http://anonymous@test.com'
246: # Subclass.site # => 'http://anonymous@test.com'
247: # Subclass.site.user = 'david' # => TypeError: can't modify frozen object
248: #
249: if defined?(@site)
250: @site
251: elsif superclass != Object && superclass.site
252: superclass.site.dup.freeze
253: end
254: end
Sets the URI of the REST resources to map for this class to the value in the site argument. The site variable is required for Active Resource‘s mapping to work.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 258
258: def site=(site)
259: @connection = nil
260: if site.nil?
261: @site = nil
262: else
263: @site = create_site_uri_from(site)
264: @user = URI.decode(@site.user) if @site.user
265: @password = URI.decode(@site.password) if @site.password
266: end
267: end
Options that will get applied to an SSL connection.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 365
365: def ssl_options=(opts={})
366: @connection = nil
367: @ssl_options = opts
368: end
Gets the number of seconds after which requests to the REST API should time out.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 346
346: def timeout
347: if defined?(@timeout)
348: @timeout
349: elsif superclass != Object && superclass.timeout
350: superclass.timeout
351: end
352: end
Sets the number of seconds after which requests to the REST API should time out.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 340
340: def timeout=(timeout)
341: @connection = nil
342: @timeout = timeout
343: end
Gets the \user for REST HTTP authentication.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 286
286: def user
287: # Not using superclass_delegating_reader. See +site+ for explanation
288: if defined?(@user)
289: @user
290: elsif superclass != Object && superclass.user
291: superclass.user.dup.freeze
292: end
293: end
Test for equality. Resource are equal if and only if other is the same object or is an instance of the same class, is not new?, and has the same id.
ryan = Person.create(:name => 'Ryan') jamie = Person.create(:name => 'Jamie') ryan == jamie # => false (Different name attribute and id) ryan_again = Person.new(:name => 'Ryan') ryan == ryan_again # => false (ryan_again is new?) ryans_clone = Person.create(:name => 'Ryan') ryan == ryans_clone # => false (Different id attributes) ryans_twin = Person.find(ryan.id) ryan == ryans_twin # => true
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 817
817: def ==(other)
818: other.equal?(self) || (other.instance_of?(self.class) && other.id == id && other.prefix_options == prefix_options)
819: end
Coerces to a hash for JSON encoding.
The options are passed to the to_json method on each attribute, so the same options as the to_json methods in Active Support.
person = Person.new(:first_name => "Jim", :last_name => "Smith")
person.to_json
# => {"first_name": "Jim", "last_name": "Smith"}
person.to_json(:only => ["first_name"])
# => {"first_name": "Jim"}
person.to_json(:except => ["first_name"])
# => {"last_name": "Smith"}
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 964
964: def as_json(options = nil)
965: attributes.as_json(options)
966: end
Returns a \clone of the resource that hasn‘t been assigned an id yet and is treated as a \new resource.
ryan = Person.find(1) not_ryan = ryan.clone not_ryan.new? # => true
Any active resource member attributes will NOT be cloned, though all other attributes are. This is to prevent the conflict between any prefix_options that refer to the original parent resource and the newly cloned parent resource that does not exist.
ryan = Person.find(1)
ryan.address = StreetAddress.find(1, :person_id => ryan.id)
ryan.hash = {:not => "an ARes instance"}
not_ryan = ryan.clone
not_ryan.new? # => true
not_ryan.address # => NoMethodError
not_ryan.hash # => {:not => "an ARes instance"}
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 747
747: def clone
748: # Clone all attributes except the pk and any nested ARes
749: cloned = attributes.reject {|k,v| k == self.class.primary_key || v.is_a?(ActiveResource::Base)}.inject({}) do |attrs, (k, v)|
750: attrs[k] = v.clone
751: attrs
752: end
753: # Form the new resource - bypass initialize of resource with 'new' as that will call 'load' which
754: # attempts to convert hashes into member objects and arrays into collections of objects. We want
755: # the raw objects to be cloned so we bypass load by directly setting the attributes hash.
756: resource = self.class.new({})
757: resource.prefix_options = self.prefix_options
758: resource.send :instance_variable_set, '@attributes', cloned
759: resource
760: end
Deletes the resource from the remote service.
my_id = 3 my_person = Person.find(my_id) my_person.destroy Person.find(my_id) # 404 (Resource Not Found) new_person = Person.create(:name => 'James') new_id = new_person.id # => 7 new_person.destroy Person.find(new_id) # 404 (Resource Not Found)
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 880
880: def destroy
881: connection.delete(element_path, self.class.headers)
882: end
Duplicate the current resource without saving it.
my_invoice = Invoice.create(:customer => 'That Company') next_invoice = my_invoice.dup next_invoice.new? # => true next_invoice.save next_invoice == my_invoice # => false (different id attributes) my_invoice.customer # => That Company next_invoice.customer # => That Company
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 844
844: def dup
845: self.class.new.tap do |resource|
846: resource.attributes = @attributes
847: resource.prefix_options = @prefix_options
848: end
849: end
Returns the serialized string representation of the resource in the configured serialization format specified in ActiveResource::Base.format. The options applicable depend on the configured encoding format.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 971
971: def encode(options={})
972: case self.class.format
973: when ActiveResource::Formats[:xml]
974: self.class.format.encode(attributes, {:root => self.class.element_name}.merge(options))
975: else
976: self.class.format.encode(attributes, options)
977: end
978: end
Tests for equality (delegates to ==).
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 822
822: def eql?(other)
823: self == other
824: end
Evaluates to true if this resource is not new? and is found on the remote service. Using this method, you can check for resources that may have been deleted between the object‘s instantiation and actions on it.
Person.create(:name => 'Theodore Roosevelt') that_guy = Person.find(:first) that_guy.exists? # => true that_lady = Person.new(:name => 'Paul Bean') that_lady.exists? # => false guys_id = that_guy.id Person.delete(guys_id) that_guy.exists? # => false
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 900
900: def exists?
901: !new? && self.class.exists?(to_param, :params => prefix_options)
902: end
Delegates to id in order to allow two resources of the same type and \id to work with something like:
[Person.find(1), Person.find(2)] & [Person.find(1), Person.find(4)] # => [Person.find(1)]
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 828
828: def hash
829: id.hash
830: end
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.
my_attrs = {:name => 'J&J Textiles', :industry => 'Cloth and textiles'}
my_attrs = {:name => 'Marty', :colors => ["red", "green", "blue"]}
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
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 1016
1016: def load(attributes)
1017: raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
1018: @prefix_options, attributes = split_options(attributes)
1019: attributes.each do |key, value|
1020: @attributes[key.to_s] =
1021: case value
1022: when Array
1023: resource = find_or_create_resource_for_collection(key)
1024: value.map do |attrs|
1025: if attrs.is_a?(String) || attrs.is_a?(Numeric)
1026: attrs.duplicable? ? attrs.dup : attrs
1027: else
1028: resource.new(attrs)
1029: end
1030: end
1031: when Hash
1032: resource = find_or_create_resource_for(key)
1033: resource.new(value)
1034: else
1035: value.dup rescue value
1036: end
1037: end
1038: self
1039: end
A method to determine if the resource a \new object (i.e., it has not been POSTed to the remote service yet).
not_new = Computer.create(:brand => 'Apple', :make => 'MacBook', :vendor => 'MacMall') not_new.new? # => false is_new = Computer.new(:brand => 'IBM', :make => 'Thinkpad', :vendor => 'IBM') is_new.new? # => true is_new.save is_new.new? # => false
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 775
775: def new?
776: id.nil?
777: end
A method to \reload the attributes of this object from the remote web service.
my_branch = Branch.find(:first) my_branch.name # => "Wislon Raod" # Another client fixes the typo... my_branch.name # => "Wislon Raod" my_branch.reload my_branch.name # => "Wilson Road"
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 991
991: def reload
992: self.load(self.class.find(to_param, :params => @prefix_options).attributes)
993: end
A method to determine if an object responds to a message (e.g., a method call). In Active Resource, a Person object with a name attribute can answer true to my_person.respond_to?(:name), my_person.respond_to?(:name=), and my_person.respond_to?(:name?).
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 1047
1047: def respond_to?(method, include_priv = false)
1048: method_name = method.to_s
1049: if attributes.nil?
1050: return super
1051: elsif attributes.has_key?(method_name)
1052: return true
1053: elsif ['?','='].include?(method_name.last) && attributes.has_key?(method_name.first(-1))
1054: return true
1055: end
1056: # super must be called at the end of the method, because the inherited respond_to?
1057: # would return true for generated readers, even if the attribute wasn't present
1058: super
1059: end
A method to \save (POST) or \update (PUT) a resource. It delegates to create if a \new object, update if it is existing. If the response to the \save includes a body, it will be assumed that this body is XML for the final object as it looked after the \save (which would include attributes like created_at that weren‘t part of the original submit).
my_company = Company.new(:name => 'RoleModel Software', :owner => 'Ken Auer', :size => 2) my_company.new? # => true my_company.save # sends POST /companies/ (create) my_company.new? # => false my_company.size = 10 my_company.save # sends PUT /companies/1 (update)
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 864
864: def save
865: new? ? create : update
866: end
Allows Active Resource objects to be used as parameters in Action Pack URL generation.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 791
791: def to_param
792: id && id.to_s
793: end
Converts the resource to an XML string representation.
The options parameter is handed off to the to_xml method on each attribute, so it has the same options as the to_xml methods in Active Support.
my_group = SubsidiaryGroup.find(:first) my_group.to_xml # => <?xml version="1.0" encoding="UTF-8"?> # <subsidiary_group> [...] </subsidiary_group> my_group.to_xml(:dasherize => true) # => <?xml version="1.0" encoding="UTF-8"?> # <subsidiary-group> [...] </subsidiary-group> my_group.to_xml(:skip_instruct => true) # => <subsidiary_group> [...] </subsidiary_group>
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 936
936: def to_xml(options={})
937: attributes.to_xml({:root => self.class.element_name}.merge(options))
938: end
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 1097
1097: def collection_path(options = nil)
1098: self.class.collection_path(options || prefix_options)
1099: end
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 1063
1063: def connection(refresh = false)
1064: self.class.connection(refresh)
1065: end
Create (i.e., \save to the remote service) the \new resource.
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 1075
1075: def create
1076: connection.post(collection_path, encode, self.class.headers).tap do |response|
1077: self.id = id_from_response(response)
1078: load_attributes_from_response(response)
1079: end
1080: end
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 1093
1093: def element_path(options = nil)
1094: self.class.element_path(to_param, options || prefix_options)
1095: end
# File vendor/rails/activeresource/lib/active_resource/base.rb, line 1082
1082: def load_attributes_from_response(response)
1083: if response['Content-Length'] != "0" && response.body.strip.size > 0
1084: load(self.class.format.decode(response.body))
1085: end
1086: end