Search code examples
ruby-on-railsrubyredminehelperredmine-plugins

How to add/override method to helper


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:

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:

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.


Solution

  • 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