2012-03-11 52 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