此问题始于here。但随着我对托尔的了解越来越多,我发生了很大的变化。
我正在尝试创建一个带有参数的Thor :: Group子命令。奇怪的是,如果没有参数,它就有效。
我可以使用Thor :: Group作为子命令吗?
当我输入foo counter
富/仓/富
module Foo
class CLI < Thor
register(Counter, 'counter', 'counter', 'Count up from the 1.')
end
class Counter < Thor::Group
desc "Prints 1 2"
def one
puts 1
end
def two
puts 2
end
end
end
Foo::CLI.start
但是当我输入foo counter 5
module Foo
class CLI < Thor
register(Counter, 'counter', 'counter <number>', 'Count up from the input.')
end
class Counter < Thor::Group
argument :number, :type => :numeric, :desc => "The number to start counting"
desc "Prints 2 numbers based on input"
def one
puts number + 0
end
def two
puts number + 1
end
end
end
Foo::CLI.start
它回复:counter was called incorrectly. Call as foo counter number
答案 0 :(得分:5)
我有一个解决方案。而不是使用Thor :: Group我正在使用Invocations
bin / foo看起来像这样:
#!/usr/bin/env ruby
require 'foo'
Foo::CLI.start
lib / cli.rb - 将'generate'注册为基本命令的子任务,foo:
module Foo
class CLI < Thor
register(Generate, 'generate', 'generate [something]', 'Type foo generate for more help.')
end
end
lib / generate.rb如下所示:
module Foo
class Generate < Thor
desc "project [name]", "Prints the project making step"
def project(name)
puts "making first project file #{name}"
invoke :config
invoke :project_sub
end
desc "config [name]", "Prints the config making step"
def config(name)
puts "making first config file #{name}"
invoke :project_sub
end
desc "project_sub [name]", "Prints the project_sub making step"
def project_sub(name)
puts "making subsystem file #{name}"
end
def self.banner(task, namespace = false, subcommand = true)
task.formatted_usage(self, true, subcommand).split(':').join(' ')
end
end
end
现在我可以输入:foo generate project fred
它将输出:
> making first project file fred
> making first config file fred
> making subsystem file fred
注意横幅覆盖。这意味着键入:foo generate project
包含无效或缺少的args将提供正确的帮助消息:
"project" was called incorrectly. Call as "foo generate project [name]".
而不是
"project" was called incorrectly. Call as "foo project [name]".