2012-03-11 88 views
0

我想重写中的资源的方法就像在这个问题解释说:Remove .xml extension from ActiveResource request这一个: i want to use a REST api, i cannot manage to set active resource to use it无法覆盖/猴补丁与导轨一个Rails 3.1.3方法

为此我测试:

在我的应用程序名为active_resource.rb用下面的代码文件/配置/在itializers /文件夹中创建:

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方法元素路径?

UPDATE

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

如果我把base.rb文件与我的类和方法在lib/active_resource /它破坏我的应用程序。我无法启动轨道服务器了

+0

如果您在重写它之前尝试要求ActiveResource,该怎么办? 'require“active_resource”'。它会有帮助吗? – cutalion 2012-03-11 20:26:52

+0

没有帮助:/ – Syl 2012-03-11 23:31:02

回答

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 
+0

它的工作原理,但我只是跳了一次,因为我将使用此API的倍数模型。 – Syl 2012-03-12 15:04:43

+1

@Sylario,没有问题,它只是Ruby继承(请参阅更新的答案):) – 2012-03-12 15:16:10

+0

Thx很多!猴子补丁终于奏效了!我只需要自我。在前面,我想它与实例/模块的东西有关,所以非常感谢。 – Syl 2012-03-12 15:28:55