Search code examples
rubythor

How to add --help, -h flag to Thor command?


I created a Thor class inside a Ruby executable, and it correctly shows the help when using ./foo help bar.

To make it more intuitive (for the sanity of my users), I'd also like to support ./foo bar --help and ./foo bar -h. When I do that, I get:

ERROR: "foo bar" was called with arguments ["--help"]
Usage: "foo bar"

I could manually do method_option :help, ... and handle it inside the bar method, but I hope there would be an easier way to do that (redirecting that command to ./foo help bar).

Does anyone know a simple and easy way to do this?


Solution

  • Assuming Foo is your class that inherits from Thor, you can call the following somewhere before Foo.start:

    help_commands = Thor::HELP_MAPPINGS + ["help"]
    # => ["-h", "-?", "--help", "-D"]
    
    if help_commands.any? { |cmd| ARGV.include? cmd }
      help_commands.each do |cmd|
        if match = ARGV.delete(cmd)
          ARGV.unshift match
        end
      end
    end
    

    Rather than going into Thor and patching some method to have different ARGV-parsing behavior, this kind of cheats by moving any help commands to the front of the list.