On Ruby's Thor, How to show the command usage from within the application

+1 vote
asked Sep 12, 2017 by leon-waldman

I'm building a CLI using Ruby and Thor and I would like to print on the screen the command usage if no option is passed.

Something on the line of the pseudo code bellow:

Class Test < Thor
  desc 'test', 'test'
  options :run_command

  def run_command
    if options.empty?
      # Print Usage
    end
  end
end

Im currently using the following hack (and I'm not proud of it! =P):

Class Test < Thor
  desc 'test', 'test'
  options :run_command

  def run_command
    if options.empty?
      puts `my_test_command help run_command`
    end
  end
end

What would be the proper way to do this?

1 Answer

+2 votes
answered Sep 12, 2017 by simple-lime

You can use command_help to display the help information for the command:

require 'thor'

class Test < Thor
  desc 'run_command --from=FROM', 'test usage help'
  option :from
  def run_command
    unless options[:from]
      Test.command_help(Thor::Base.shell.new, 'run_command')
      return
    end

    puts "Called command from #{options[:from]}"
  end
end

Test.start

and then running with no options:

$ ruby example.rb run_command
Usage:
  example.rb run_command --from=FROM

Options:
  [--from=FROM]

test usage help

and running with the option:

$ ruby example.rb run_command --from=somewhere
Called command from somewhere
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...