Skip to content
Rafael Mendonça França edited this page Aug 21, 2023 · 25 revisions

Guided Tour

On this page, you will find basic instructions on how to get started. Further information is available in the following subpages.

  • Getting Started - Introduction to Thor conventions. Includes a simple example with explanations of tasks, parameters, and options.
  • Method Options - Explains what you can do when defining options for Thor tasks.
  • Invocations - Shows how you can have Thor tasks depend on other Thor tasks without accidentally invoking the same task more than once using Thor's invocation-dependency features.
  • Groups - Thor::Group is an easy way to run multiple tasks as a sequence.
  • Actions - Thor::Actions are helpers for your Thor tasks that make typical actions, like file system interaction or command line user dialogue, easier.
  • Namespaces - You can define your Thor classes under Namespaces
  • Making An Executable - Run your Thor task directly, without the thor command.
  • Generators - An example using Thor to define custom generators (aka Rails 3 generators).
  • Subcommands - Create git like subcommands using Thor's subcommand method

Basic Usage

Map options to a class. Simply create a class with the appropriate annotations and have options automatically map to functions and parameters.

Example:

class App < Thor                                                 # [1]
  package_name "App"                                             # [2]
  map "-L" => :list                                              # [3]
  
  desc "install APP_NAME", "install one of the available apps"   # [4]
  method_options :force => :boolean, :alias => :string           # [5]
  def install(name)
    user_alias = options[:alias]
    if options.force?
      # do something
    end
    # other code
  end
  
  desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
  def list(search="")
    # list everything
  end
end

Thor automatically maps commands as such:

thor app:install myname --force

That gets converted to:

App.new.install("myname")
# with {'force' => true} as options hash
  1. Inherit from Thor to turn a class into an option mapper.
  2. Allows a Thor application to be named and be recognized on console/debug output.
  3. Map additional non-valid identifiers to specific methods. In this case, convert -L to :list
  4. Describe the method immediately below. The first parameter is the usage information, and the second parameter is the description.
  5. Provide any additional method options.

Further Reading

Thor offers many scripting possibilities beyond these examples. Be sure to read through the documentation and specs to get a better understanding of the options available. To see how users use Thor, you can search Github or search Gisthub for 'require thor'. The code you find is user submitted content that has no warranty of correct usage of Thor.

Clone this wiki locally