Search code examples
rubycommand-linethor

How can I use a flag as a command with Thor


Given a Ruby program using Thor, how can I implement a method that gets called when an argument that looks like a flag is called.

For example, if I run this on the command line:

mycmd --version

I would like to execute the code:

desc 'version', 'Print version number'
def version
  puts "mycmd version #{Mycmd::VERSION}"
end

Solution

  • You can make a "top level" default task, which examines its arguments and outputs the correct thing:

    class MyThing < Thor
      desc "meta", "Information about the task itself"
      argument :name
      def meta
        if name == "--version"
          puts "v 1.1.1"
        elsif name == "--author"
          puts "meagar"
        end
      end
      default_task :meta
    end