How do I monkey-patch a Jekyll extension or plugin?

旧时模样 提交于 2019-12-10 13:37:28

问题


I'd like to override a gem method (a Jekyll extension) that looks like this:

File: lib/jekyll-amazon/amazon_tag.rb.

module Jekyll
  module Amazon
    class AmazonTag < Liquid::Tag
      def detail(item)
...
      end
    end
  end
end
Liquid::Template.register_tag('amazon', Jekyll::Amazon::AmazonTag)

I have placed code with the same structure in my project in the folder config/initializers/presentation.rb _plugins/presentation.rb. If I change the name of the method detail to a new name, it works, but I can't get it to override the name detail. What have I done wrong?

(Note: In version 0.2.2 of the jekyll-amazon gem, the detail method is private; I have changed this locally so that the method is no longer private.)


回答1:


You can use alias_method

module Jekyll
  module Amazon
    class AmazonTag < Liquid::Tag

      alias_method :old_detail, :detail

      def detail(item)
        # do your stuff here
        # eventually pass your stuff to old method
        old_detail(item)
      end

    end
  end
end
Liquid::Template.register_tag('amazon', Jekyll::Amazon::AmazonTag)


来源:https://stackoverflow.com/questions/41567687/how-do-i-monkey-patch-a-jekyll-extension-or-plugin

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