2013-05-31 35 views
0

我想用我的插件覆蓋輔助方法。我試圖創建一個新的幫手模塊,其方法應該像這樣覆蓋:如何向幫手添加/覆蓋方法

myplugin/app/helpers/issues_helper.rb 

module IssuesHelper 
    def render_custom_fields_rows(issus) 
    'it works!'.html_safe 
    end 
end 

但是這不起作用。核心方法仍然適用於適當的觀點。

哈克解決方案:

issues_helper_patch.rb 

module IssuesHelperPatch 
    def self.included(receiver) 
    receiver.send :include, InstanceMethods 

    receiver.class_eval do 
     def render_custom_fields_rows(issue) 
     "It works".html_safe 
     end 
    end 
    end 
end 

init.rb 

Rails.configuration.to_prepare do 
    require 'issues_helper_patch' 
    IssuesHelper.send  :include, IssuesHelperPatch 
end 

這是因爲黑客在正常的方式方法應該是InstanceMethods模塊IssuesHelperPatch模塊。

+0

'return'是隱含的,如果你的價值是最後一行。包括它往往表明它出於某種原因並可能導致混淆。 – tadman

+0

你確定這是正在執行的方法嗎?當你說「不起作用」時,你並不具體。 – tadman

+0

@tadman我剛剛刪除了很多代碼,以使示例更小,因此您的建議無關緊要。謝謝。 – freemanoid

回答

0

這是恕我直言這個問題很好解決

issues_helper_patch.rb 
module IssuesHelperPatch 
    module InstanceMethods 
    def render_custom_fields_rows_with_message(issue) 
     "It works".html_safe 
    end 
    end 

    def self.included(receiver) 
    receiver.send :include, InstanceMethods 

    receiver.class_eval do 
     alias_method_chain :render_custom_fields_rows, :message 
    end 
    end 
end 

init.rb 

Rails.configuration.to_prepare do 
    require 'issues_helper_patch' 
    IssuesHelper.send  :include, IssuesHelperPatch 
end 
+0

這不是一個好的解決方案。你應該使用元編程,這對於你想要做的事情來說是理想的。 –

3
IssuesHelper.class_eval do 
    def render_custom_fields_rows(issus) 
    'it works!'.html_safe 
    end 
end 
+0

好吧,這工作,但它看起來像一個黑客。問題已更新。 – freemanoid

+0

@freemanoid這不是黑客。這是Ruby Metaprogramming。 –