Skip to content
coderifous edited this page Apr 22, 2011 · 25 revisions

Guided Tour

  • 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::Groups are 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 (ala Rails 3 generators).

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]
  map "-L" => :list                                              # [2]
  
  desc "install APP_NAME", "install one of the available apps"   # [3]
  method_options :force => :boolean, :alias => :string           # [4]
  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. Map additional non-valid identifiers to specific methods. In this case, convert -L to :list
  3. Describe the method immediately below. The first parameter is the usage information, and the second parameter is the description.
  4. Provide any additional options that will be available the instance 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.

Clone this wiki locally