Question

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
Was it helpful?

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top