Skip to content
chikamichi edited this page Aug 2, 2011 · 9 revisions

Thor has a special class called Thor::Group. All of the tasks defined in a Thor::Group are invoked together as a sequence, in the order that they were defined. The example from Invocations could be rewritten using Thor::Group as:

class Counter < Thor::Group
  desc "Prints 1 2 3"

  def one
    puts 1
  end

  def two
    puts 2
  end

  def three
    puts 3
  end
end

When invoked:

thor counter
# prints "1 2 3"

Note: when using Thor::Group, the description you provide (using the method desc) is for the entire class, as opposed to providing a description for each task.

Also, Thor::Group can parse arguments and options as Thor tasks:

class Counter < Thor::Group
  # number will be available as attr_accessor
  argument :number, :type => :numeric, :desc => "The number to start counting"
  desc "Prints the 'number' given upto 'number+2'"

  def one
    puts number + 0
  end

  def two
    puts number + 1
  end

  def three
    puts number + 2
  end
end

The counter above expects one parameter and has the folling outputs:

thor counter 5
# Prints "5 6 7"

thor counter 11
# Prints "11 12 13"

You can also give options to Thor::Group, but instead of using method_option and method_options, you should use class_option and class_options. Both argument and class_options methods are available to Thor class as well.

Thor::Group is a great tool to create generators, since you can define several steps which are invoked in the order they are defined (Thor::Group is the tool used for generators in Rails 3.0).

Clone this wiki locally