从ActiveResource请求中删除.xml扩展名

我正在尝试使用ActiveResource来使用来自第三方API的xml数据。 我可以使用RESTClient应用程序成功进行身份validation和发出请求。 我编写了我的应用程序,当我提出请求时,我收到404错误。 我补充说:

ActiveResource::Base.logger = Logger.new(STDERR) 

到我的development.rb文件并找出问题所在。 API使用xml数据响应不以xml结尾的请求。 EG,这适用于RESTClient:

 https://api.example.com/contacts 

但ActiveResource正在发送此请求

 https://api.example.com/contacts.xml 

无论如何,从ActiveResource生成的请求中删除扩展名是否“很好”?

谢谢

您可能需要覆盖模型中的element_path方法。

根据API,目前的定义如下:

 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}/#{id}.#{format.extension}#{query_string(query_options)}" end 

删除。#{format.extension}部分可能会满足您的需求。

您可以从以下路径中排除格式字符串:

 class MyModel < ActiveResource::Base self.include_format_in_path = false end 

您可以覆盖ActiveResource :: Base的方法

在/ lib / active_resource / extend /目录中添加此lib不要忘记取消注释
config / application.rb中的 “config.autoload_paths + =%W(#{config.root} / lib)”

 module ActiveResource #:nodoc: module Extend module WithoutExtension module ClassMethods def element_path_with_extension(*args) element_path_without_extension(*args).gsub(/.json|.xml/,'') end def new_element_path_with_extension(*args) new_element_path_without_extension(*args).gsub(/.json|.xml/,'') end def collection_path_with_extension(*args) collection_path_without_extension(*args).gsub(/.json|.xml/,'') end end def self.included(base) base.class_eval do extend ClassMethods class << self alias_method_chain :element_path, :extension alias_method_chain :new_element_path, :extension alias_method_chain :collection_path, :extension end end end end end end 

在模型中

 class MyModel < ActiveResource::Base include ActiveResource::Extend::WithoutExtension end 

在逐个类的基础上覆盖本答案中提到的_path访问器要简单得多,而不是在应用程序范围内修补ActiveResource,这可能会干扰依赖于ActiveResource的其他资源或gem。

只需将方法直接添加到您的类:

 class Contact < ActiveResource::Base def element_path super.gsub(/\.xml/, "") end def new_element_path super.gsub(/\.xml/, "") end def collection_path super.gsub(/\.xml/, "") end end 

如果您在同一API中访问多个RESTful资源,则应定义自己的基类,其中可以包含公共配置。 对于自定义_path方法,这是一个更好的地方:

 # app/models/api/base.rb class Api::Base < ActiveResource::Base self.site = "http://crazy-apis.com" self.username = "..." self.password = "..." self.prefix = "/my-api/" # Strip .xml extension off generated URLs def element_path super.gsub(/\.xml/, "") end # def new_element_path... # def collection_path... end # app/models/api/contact.rb class Api::Contact < Api::Base end # app/models/api/payment.rb class Api::Payment < Api::Base end # Usage: Api::Contact.all() # GET http://crazy-apis.com/my-api/contacts Api::Payment.new().save # POST http://crazy-apis.com/my-api/payments