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

1

6

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.)

Foulup answered 10/1, 2017 at 11:26 Comment(2)
Looks like we got lucky: jekyll-amazon now supports custom templates.Esophagitis
Yes, but I still want to know (for my own knowledge) how to override the original gem.Foulup
S
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)
Sexennial answered 10/1, 2017 at 14:19 Comment(5)
put it at the root of your jekyll site in a _plugins folderSexennial
I'm getting jekyll 3.3.1 | Error: undefined method 'detail' for class Jekyll::Amazon::AmazonTagFoulup
My _config.yml has gems: ['jekyll-paginate', 'jekyll-amazon'], and I see the base plugin I am overriding when I do a gem list.Foulup
If I use new_detail rather than detail in _plugins/presentation.rb and update my html to use this new tag, it works. But I can't seem to "override" the old detail tag.Foulup
Marking this as correct because I think this the closest you can get.Foulup

© 2022 - 2024 — McMap. All rights reserved.