如何在使用活动资源时从URL中删除.xml和.json

当我在活动资源中进行映射时,它对Ruby on Rails的默认请求总是自动在URL的末尾添加扩展。 例如:我想通过映射从Ruby on Rails获取用户资源,如下所示:

 class user <ActiveResource :: Base
   self.site ='http:// localhost:3000'
结束

我需要的东西,我只是希望它通过没有扩展名的url

  HTTP://本地主机:3000 /用户 

相比之下,它会自动添加url末尾的扩展名

  HTTP://本地主机:3000 / user.xml 

当我从活动资源映射发出请求时,如何省略url的扩展名?

起初,我确实使用了@Joel AZEMAR的答案,并且在我开始使用PUT之前它运行良好。 在.json / .xml中添加PUT。

这里的一些研究表明,使用ActiveResource::Base#include_format_in_path选项对我来说效果更好。

没有include_format_in_path:

 class Foo < ActiveResource::Base self.site = 'http://localhost:3000' end Foo.element_path(1) => "/foo/1.json" 

使用include_format_in_path:

 class Foo < ActiveResource::Base self.include_format_in_path = false self.site = 'http://localhost:3000' end Foo.element_path(1) => "/foo/1" 

您可以覆盖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 

您可以通过在类中重写两个ActiveResource的方法来完成此操作:

 class User < ActiveResource::Base class << self 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}#{query_string(query_options)}" end def collection_path(prefix_options = {}, query_options = nil) prefix_options, query_options = split_options(prefix_options) if query_options.nil? "#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}" end end self.site = 'http://localhost:3000' end