Skip to content

Subcommands

ellemenno edited this page Oct 12, 2020 · 5 revisions

You can create subcommands using Thor's subcommand method. The subcommand maps a given subcommand to another Thor subclass

Simple Usage

The simplest usage for a subcommand will be something like:

myapp.rb

require 'thor'
require "sub"

class MyApp < Thor
  desc "parentcommand SUBCOMMAND", "Some Parent Command"
  subcommand "sub", Sub
end

MyApp.start

sub.rb

class Sub < Thor
  desc "command", "an example task"
  def command
    puts "I'm a thor task!"
  end
end

Subcommands that work correctly with help

#!/usr/bin/env ruby

require 'thor'

class SubCommandBase < Thor
  def self.banner(command, namespace = nil, subcommand = false)
    "#{basename} #{subcommand_prefix} #{command.usage}"
  end

  def self.subcommand_prefix
    self.name.gsub(%r{.*::}, '').gsub(%r{^[A-Z]}) { |match| match[0].downcase }.gsub(%r{[A-Z]}) { |match| "-#{match[0].downcase}" }
  end
end

module App
  class Docs < SubCommandBase
    desc "create", "create docs"
    def create
      # create
    end

    desc "publish", "publish docs"
    def publish
      # publish
    end
  end

  class CLI < Thor
    desc "docs", "create and publish docs"
    subcommand "docs", Docs
  end
end

App::CLI.start

This is how the subcommands for the above code snippet works:

When you invoke test.rb without any arguments or options

$ ./test.rb

Output:

Commands:
  test.rb docs            # create and publish docs
  test.rb help [COMMAND]  # Describe available commands or one specific command

When you invoke with the subcommand name option

$ ./test.rb docs

Output:

Commands:
  test.rb docs create          # create docs
  test.rb docs help [COMMAND]  # Describe subcommands or one specific subcommand
  test.rb docs publish         # publish docs

When you invoke the help of subcommand

$ ./test.rb help docs

Output:

Commands:
  test.rb docs create          # create docs
  test.rb docs help [COMMAND]  # Describe subcommands or one specific subcommand
  test.rb docs publish         # publish docs
$ ./test.rb docs help create
Usage:
  test.rb docs create

create docs

Reference

Clone this wiki locally