Brad Herman
Brad Herman

Reputation: 10593

ActiveResource Suffix

With ActiveResource, a call to MyObject.find(id) gets "[self.site]/[self.prefix]/:id.[self.format]". However, the API we're accessing is configured slightly differently. Instead of id.file_type we need to access "[self.site]/:id/[self.suffix].[self.format]".

ie: get http://api_path/:id/tool.json

Is there any way to configure activeresource for this scenario? I'm not finding much in the documentation.

Upvotes: 2

Views: 806

Answers (1)

Joshua Scott
Joshua Scott

Reputation: 663

ActiveResource::Base.element_path is the method that creates the path:

def element_path(id, prefix_options = {}, query_options = nil)
  prefix_options, query_options = split_options(prefix_options) if query_options.nil?
  "#{prefix(prefix_options)}#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
end

I would create a class that redefines element_path, something like this:

class CustomApiPath < ActiveResource::Base
  def element_path(id, prefix_options = {}, query_options = nil)
    prefix_options, query_options = split_options(prefix_options) if query_options.nil?
    "#{prefix(prefix_options)}#{URI.escape id.to_s}/#{collection_name}.#{format.extension}#{query_string(query_options)}"
  end
end

(warning: not tested) and then the other ActiveResource models would inherit from CustomApiPath rather than ActiveResource::Base.

Upvotes: 3

Related Questions