无法使用rails 3.1.3覆盖/猴子修补rails方法

时间:2012-03-11 13:20:59

标签: ruby-on-rails overloading monkeypatching

我正在尝试覆盖此问题中解释的活动资源方法:Remove .xml extension from ActiveResource request和此问题: i want to use a REST api, i cannot manage to set active resource to use it

这样做我测试了:

在我的应用程序的/ config / in itializers /文件夹中创建一个名为active_resource.rb的文件,其中包含以下代码:

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

在我的模型中添加方法。这是我的型号代码:

class Player < ActiveResource::Base
  def element_path(id, prefix_options = {}, query_options = nil)
    check_prefix_options(prefix_options)

    prefix_options, query_options = split_options(prefix_options) if query_options.nil?
    "#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}#{query_string(query_options)}"
  end
  self.site = "http://ws.maniaplanet.com/"
  self.user="**********"
  self.password="*********"
end

要验证我的自定义代码的覆盖,我尝试使用

puts  "called this method"

ActionController::Base.logger.info "called this method"

它从未奏效。

为什么我不能覆盖rails方法元素路径?

更新

在取消注释application.rb中的config.autoload_paths += %W(#{config.root}/extras)行后,尝试将active_resource.rb置于额外。没有变化

如果我将base.rb文件与我的类和方法放在lib / active_resource /中,它会破坏我的应用程序。我再也无法启动rails服务器了

1 个答案:

答案 0 :(得分:1)

你应该覆盖类方法,而不是实例1,所以:

class Player < ActiveResource::Base

  def self.element_path(id, prefix_options = {}, query_options = nil)
    #...
  end

end

如果您只从Player型号发出请求,那就足够了。

如果你想对任何模型采用这种行为,你应该再次使用类方法ActiveResource::Base

# config/initializers/active_resource_patch.rb
class ActiveResource::Base

  def self.element_path(id, prefix_options = {}, query_options = nil)
    #...
  end

end