【问题标题】:How to add/override method to helper如何向助手添加/覆盖方法
【发布时间】:2013-05-31 19:58:00
【问题描述】:

我想用我的插件覆盖辅助方法。我试图创建一个新的辅助模块,其方法应该像这样覆盖:

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

这是 hack,因为在正常情况下,方法应该在 IssuesHelperPatch 模块的 InstanceMethods 模块中。

【问题讨论】:

  • 如果您的值在最后一行,return 是隐含的。包含它确实倾向于表明它的存在是有原因的,并且可能会导致混乱。
  • 你确定这是正在执行的方法吗?当您说“不起作用”时,您并不具体。
  • @tadman 我刚刚删除了很多代码以使示例更小,因此您的建议无关紧要。谢谢。
  • 这个方法应该在问题/显示视图中执行,它的结果应该在页面上。所以我倾向于相信这个方法正在执行。

标签: ruby-on-rails ruby redmine helper redmine-plugins


【解决方案1】:
IssuesHelper.class_eval do
  def render_custom_fields_rows(issus)
    'it works!'.html_safe
  end
end

【讨论】:

    【解决方案2】:

    恕我直言,这是解决此问题的解决方案:

    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
    

    【讨论】:

    • 这不是一个好的解决方案。您应该使用非常适合您想要做的事情的元编程。
    猜你喜欢
    • 1970-01-01
    • 2014-11-20
    • 2019-02-05
    • 2013-01-21
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    相关资源
    最近更新 更多