Search code examples
rubyrubygemsthor

How do I Monkey-patch a gem with a hierarchy?


I'm trying to add a new method to the Thor gem. Specifically, I want to add a method to Thor::Shell::Basic. In my gem based on thor, in bin/mycommand, I have this:

require 'thor'
require 'ext/thor/extension'
Thor.include ThorExtensions::Thor::Shell::Basic
MyCommand.start

In lib/ext/thor/extension.rb, I have:

module ThorExtensions
  module Thor
    module Shell
      module Basic
        def extension_method

When I call extension_method, I get an error that says it can't read an attribute of Thor::Shell::Basic (padding, specifically). When I go into Thor::Shell::Basic, in pry, I see my method listed as a method of that class, but it doesn't seem to be able to access it at runtime. Am I doing something wrong?


Solution

  • You can reopen classes in ruby:

    class Thor::Shell::Basic
      def extension_method
      end
    end
    

    Or you can inlcude your extension(s) as a module (I prefer this one):

    module MyExtension
      def extension_method
      end
    end
    
    Thor::Shell::Basic.send :include, MyExtension