Monkey patching Rails

送分小仙女□ 提交于 2021-01-28 02:51:14

问题


I need to monkey-patch one of the Rails core classes, specifically ActionView::Helpers::UrlHelper::ClassMethods.link_to method. As far as I remember there are some events fired when parts of Rails are loaded, how to add handlers for them? Or should I just put the code into initializer?


回答1:


link_to does not appear to be in ClassMethods. From here.

In config/initializers/url_helper_extensions.rb

module ActionView
  module Helpers
    module UrlHelper
      alias_method :_link_to, :link_to
      def link_to

        # Your code ...

        # Call original method if you want.
        _link_to

      end
    end
  end
end


来源:https://stackoverflow.com/questions/20465886/monkey-patching-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!