gpt4 book ai didi

ruby - 如何将 Thor::Group 注册为带参数的子命令

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:48 25 4
gpt4 key购买 nike

这道题开始于here .但随着我对雷神的了解越来越多,情况发生了很大变化。

我正在尝试创建一个带参数的 Thor::Group 子命令。奇怪的是,如果没有参数,它就可以工作。

我可以使用 Thor::Group 作为子命令吗?

这在我输入时有效:foo counter

foo/bin/foo

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

它回复:计数器调用不正确。作为 foo 计数器编号调用

最佳答案

我有一个解决方案。我没有使用 Thor::Group,而是使用了调用

bin/foo 看起来像这样:

#!/usr/bin/env ruby

require 'foo'

Foo::CLI.start

lib/cli.rb - 将“生成”注册为基本命令 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 with invalid or missing args 将给出正确的帮助信息:

"project" was called incorrectly. Call as "foo generate project [name]".

相对于

"project" was called incorrectly. Call as "foo project [name]".

关于ruby - 如何将 Thor::Group 注册为带参数的子命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com