jump to navigation

Use ActiveResource to Consume Simple Objects Over REST January 16, 2008

Posted by reidmix in ActiveResource, Code, Example, Rails.
Tags:
trackback

I’m sure that many organizations have services available via REST that are not produced by Rails and do not follow Rails conventions. That doesn’t mean you have to write your own client. For simple objects, use ActiveResource.

To take advantage of ActiveResource in this way use the ActiveResource::Base#find method. You need to find(:all), find(:first), or find(:one) but you need to pass a string of the path to the :from option along with any :params you need. If you pass a symbol as the :from option, this will not work and will employ all of the the ActiveResource::Base mechanics. A string will bypass this, for example:

class RestClient < ActiveResource::Base
  self.site = "http://java-based-service.company.com"

  def self.invoke(params = {})
    find(:one, :from => "/nonconventional/path/to/rest/service/", :params => params)
  end
end

object = RestClient.invoke(:irregular_id => 10) #=> service returns <data><name>reid</name><role>blogger</role></data>
object.name #=> reid
object.role #=> blogger

Comments»

No comments yet — be the first.