How do I monkey-patch a Jekyll extension or plugin

2019-06-18 22:54发布

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条回答
爷的心禁止访问
2楼-- · 2019-06-18 23:45

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)
查看更多
登录 后发表回答