Various ActiveResource Tips

Although you find the most of the following tips by simple googling or visiting the ActiveResource documentation, I just wanted to outline them on one single page again (mostly because of my obliviousness).

Enable logging of ActiveResource actions

Add the following to your environment.rb :

ActiveResource::Base.logger = ActiveRecord::Base.logger

 

Set different resource name

Sometimes you already have a model (e.g. ActiveRecord model) with the same name and you need to name your ActiveResource model differently. You can simply set the name of the remote resource by setting the element_name  property.

class ProjectResource < ActiveResource::Base
  self.site = "http://www.yourserviceendpoint.com"
  self.element_name = "project"
end

 

Set different resource format

To use a different resource format instead of the json  default just add to you model:

self.format = :xml

 

Set HTTP header fields

For adding you own HTTP headers, which is sometimes needed for e.g. authentication via access tokens, you can set them at class level like the following:

class ProjectResource < ActiveResource::Base
  self.site = "http://www.yourserviceendpoint.com"
  self.element_name = "project"

  # Set headers in global context
  headers['X-ACCESS-TOKEN'] = 'YOUR_ACCESS_TOKEN'
end

 

Leave a Reply

Your email address will not be published. Required fields are marked *