热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何向助手添加/覆盖方法-Howtoadd/overridemethodtohelper

Iwanttooverridethehelpermethodwithmyplugin.Itriedtocreateanewhelpermodulewithmeth

I want to override the helper method with my plugin. I tried to create a new helper module with method that should override like this:

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

myplugin/app/helpers/issues_helper.rb

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

But this doesn't work. Core method still used in appropriate view.

但这不起作用。核心方法仍在适当的视图中使用。

Hack solution:

Hack解决方案:

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

This is the hack because in normal way methods should be in InstanceMethods module of IssuesHelperPatch module.

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

2 个解决方案

#1


3  

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

#2


0  

This is IMHO good solution for this problem:

这是恕我直言这个问题的好方法:

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

推荐阅读
author-avatar
拍友2502876287
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有