Class

Base

Extends:

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 link:files/vendor/rails/activeresource/README.html.

Automated mapping

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.

Lifecycle methods

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.

Custom REST methods

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.

Validations

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.

Authentication

Many REST APIs will require authentication, usually in the form of basic HTTP authentication. Authentication can be specified by putting the credentials in the site variable of the Active Resource class you need to authenticate.

class Person < ActiveResource::Base
  self.site = "http://ryan:password@api.people.com:3000/"
end

For obvious security reasons, it is probably best if such services are available over HTTPS.

Errors & Validation

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.

Resource errors

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) # => Raises ActiveResource::ResourceNotFound
# => Response = 404

404 is just one of the HTTP error response codes that ActiveResource will handle with its own exception. The following HTTP response codes will also result in these exceptions:

200 - 399:Valid response, no exception
404:ActiveResource::ResourceNotFound
409:ActiveResource::ResourceConflict
422:ActiveResource::ResourceInvalid (rescued by save as validation errors)
401 - 499:ActiveResource::ClientError
500 - 599:ActiveResource::ServerError

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

Validation errors

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 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
# is requested with invalid values, the response is:
#
# Response (422):
# <errors type="array"><error>First cannot be empty</error></errors>
#

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.

Aliases
respond_to_without_attributes? For checking respond_to? without searching the attributes (which is faster).
set_collection_name
set_element_name
set_prefix
set_primary_key
Public Attributes
attributes
prefix_options
Public Methods
== 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.
collection_path Gets the collection path for the REST resources. If the query_options parameter is omitted, Rails will split from the prefix_options.
connection 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).
create Create a new resource instance and request to the remote service that it be saved, making it equivalent to the following simultaneous calls:
delete Deletes the resources with the ID in the id parameter.
destroy Deletes the resource from the remote service.
dup Duplicate the current resource without saving it.
element_path Gets the element path for the given ID in id. If the query_options parameter is omitted, Rails will split from the prefix options.
eql? Tests for equality (delegates to ==).
exists? 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.
exists? Asserts the existence of a resource, returning true if the resource is found.
find Core method for finding resources. Used similarly to Active Record’s find method.
format Returns the current format, default is ActiveResource::Formats::XmlFormat
format= Sets the format that attributes are sent and received in from a mime type reference. Example:
hash Delegates to id in order to allow two resources of the same type and id to work with something like:
headers
id Get the id attribute of the resource.
id= Set the id attribute of the resource.
load 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.
new Constructor method for new resources; the optional attributes parameter takes a Hash of attributes for the new resource.
new? A method to determine if the resource a new object (i.e., it has not been POSTed to the remote service yet).
prefix 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.
prefix= Sets the prefix for a resource’s nested URL (e.g., prefix/collectionname/1.xml). Default value is site.path.
prefix_source 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.
reload A method to reload the attributes of this object from the remote web service.
respond_to? 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?").
save 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).
site Gets the URI of the REST resources to map for this class. The site variable is required ActiveResource’s mapping to work.
site= Sets the URI of the REST resources to map for this class to the value in the site argument. The site variable is required ActiveResource’s mapping to work.
to_param Allows ActiveResource objects to be used as parameters in ActionPack URL generation.
to_xml A method to convert the the resource to an XML string.
Protected Methods
collection_path
connection
create Create (i.e., save to the remote service) the new resource.
element_path
id_from_response Takes a response from a typical create post and pulls the ID out
load_attributes_from_response
update Update the resource on the remote service.
Private Methods
create_site_uri_from Accepts a URI and creates the site URI from that.
find_every Find every resource
find_one Find a single resource from a one-off URL
find_or_create_resource_for Tries to find a resource for a given name; if it fails, then the resource is created
find_or_create_resource_for_collection Tries to find a resource for a given collection name; if it fails, then the resource is created
find_resource_in_modules Tries to find a resource in a non empty list of nested modules Raises a NameError if it was not found in any of the given nested modules
find_single Find a single resource from the default URL
instantiate_collection
instantiate_record
method_missing
prefix_parameters contains a set of the current prefix parameters.
query_string Builds the query string for the request.
split_options
split_options split an option hash into two hashes, one containing the prefix options, and the other containing the leftovers.
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.