Removing the file extension on ActiveResource calls

Wednesday, March 16, 2011 by Rick Thomas
Recently I was struggling with getting ActiveResource custom method calls to play nicely with a RESTful API written in .NET.  The RESTful API does not allow file extensions (.xml or .json) in requests.  By default, ActiveResource would append any request to the API with the desired content format.

I had initially gotten around this problem by overriding the ActiveResource element_path and collection_path methods.  This worked find for the standard GET, PUT, POST, and DELETE calls.  However, I ran into a situation where I needed to make custom method calls (api.rubyonrails.org/classes/ActiveResource/CustomMethods.html).  These calls use different methods (custom_element_path and custom_element_path) that are private and cannot be overridden, and as a consequence, that pesky .xml extension was back.

After a chat with Justin Weiss, the guru behind the Reactive Resource gem (github.com/justinweiss/reactive_resource), I learned about Custom Formats.  Rolling your own custom format is easy - simply copy the format you want to use from the lib/active_resource/formats directory (if you're using bundler, you can find the source for active resource with 'bundle show activeresource').  Copy that class (I used XmlFormat) into a new file, rename the class to 'CustomFormat', and change the extension method to return an empty string.  I saved custom_format.rb in my Rails project's lib/extensions folder.  ActiveResource has a bug where not having an extension doesn't work (which ReactiveResource fixes), so you'll need to install the Reactive Resource gem and use that instead of Active Resource.

In order to correctly load this extension into your project's instance of Active Resource, in config/initializers/extensions.rb, add this:

require 'extensions/sst_format'

ActionController::Base.class_eval do
  include ActiveResource::Formats::CustomFormat
end
Finally, in your models that inherit from ActiveResource, in addition to setting the model's site property, you'll need to set the format property:

self.site = "http://www.myservice.com"
self.format = :custom
This will strip out the extension from all calls to your API.  With this bit of plumbing out of the way, you're back to working on the fun stuff.

Tagged in: TechnologyDev

Comments for Removing the file extension on ActiveResource calls

Monday, July 18, 2011 by Monica:
Thanks! This was helpful.

It would be worth it to note that the reason ActiveResource doesn't work with a custom extension that is empty is that it will still add a "." to the extension.


ree-1.8.7-2011.03 :002 > Stripe::Charge.element_path("testid")
=> "/v1/charges/testid."

Leave a comment





Captcha