-
Notifications
You must be signed in to change notification settings - Fork 554
Invocations
Thor comes with an invocation-dependency system as well, that allows a task to be invoked only once. For example:
class Counter < Thor
desc "one", "Prints 1 2 3"
def one
puts 1
invoke :two
invoke :three
end
desc "two", "Prints 2 3"
def two
puts 2
invoke :three
end
desc "three", "Prints 3"
def three
puts 3
end
end
When invoking the task one:
thor counter:one
The output is
1
2
3
which means that the three
task was invoked only once.
Notice invocations do not share the same object. i.e, Thor will instantiate Counter
once to invoke the task one
, then, it instantiates another to invoke the task two
and another for task three
. This allows options and arguments to be parsed again. For example, if two
and three
have different options and both of them were given to the command line, calling invoke
enables them to be parsed each time and used accordingly by each task.
Tasks may also be invoked from other classes and options may be passed to invocations. For example:
class A < Thor
desc "list LINE", "Does A stuff"
method_option :line, :type => :string, :required => false
def list
unless options[:line].nil?
puts "Line option is #{options[:line]}"
else
puts "Line option wasn't passed"
end
end
end
class B < Thor
desc "dig NAME", "Does B stuff"
method_option :name, :type => :string
def dig
invoke 'a:list', [], :line => options[:name]
end
end
$ thor a:list --line foo
Line option is foo
$ thor a:list
Line option wasn't passed
$ thor b:dig --name bar
Line option is bar
If a task needs to be invoked more than once, the method may be called directly instead of using invocations. This is useful for situations such as setting up and tearing down test infrastructure in between test suites. For instance:
class Tests < Thor
desc('all', 'run all tests')
def all
setup()
invoke :some_test_suite
teardown()
setup()
invoke :some_other_test_suite
teardown()
# etc.
end
desc('setup', 'set up the test database')
def setup
# some setup tasks here
end
desc('teardown', 'tear down the test database')
def teardown
# some teardown tasks here
end
end
Be sure to check the documentation for the Thor class for more info.