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

时间:2009-04-20 07:05:55

标签: ruby-on-rails

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

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

我需要的东西,我只是希望它传递没有扩展名的网址,如

http://localhost:3000/user
相反,它会自动在网址末尾添加扩展名,如
http://localhost:3000/user.xml

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

3 个答案:

答案 0 :(得分:12)

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

有点research here,显示使用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"

答案 1 :(得分:4)

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

答案 2 :(得分:3)

您可以通过覆盖类中的两个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