5

这是我的 Ruby 代码:

require 'thor'
require 'thor/group'

module CLI

    class Greet < Thor
        desc 'hi', 'Say hi!'
        method_option :name, :type => :string, :description => 'Name to greet', :default => 'there'
        def hi
            puts "Hi, #{options[:name]}!"
        end

        desc 'bye', 'say bye!'
        def bye
            puts "Bye!"
        end
    end


    class Root < Thor
        register CLI::Greet, 'greet', 'greet [COMMAND]', 'Greet with a command'
    end
end


CLI::Root.start

这是输出:

C:\temp>ruby greet.rb help greet
Usage:
  greet.rb greet [COMMAND]

Greet with a command

我怎样才能让它看起来像这样?

C:\temp>ruby greet.rb help greet
Usage:
  greet.rb greet [COMMAND]
    --name Name to greet

Greet with a command
4

1 回答 1

7

你有两件事在这里发生。首先,您已将 --name 分配给一个方法,而不是整个CLI::Greet类。因此,如果您使用以下命令:

ruby greet.rb greet help hi

你得到

Usage:
  greet.rb hi

Options:
  [--name=NAME]  
                 # Default: there

Say hi!

是的,这是错误的——它在帮助中没有子命令。在 Thor 中为此提交了一个错误。但是,它正确显示了方法选项。

然而,看起来你正在寻找的是一个类方法。这是为整个CLI::Greet类定义的方法,而不仅仅是为方法定义的#hi

你会这样做:

require 'thor'
require 'thor/group'

module CLI

    class Greet < Thor
        desc 'hi', 'Say hi!'
        class_option :number, :type => :string, :description => 'Number to call', :default => '555-1212'
        method_option :name, :type => :string, :description => 'Name to greet', :default => 'there'
        def hi
            puts "Hi, #{options[:name]}! Call me at #{options[:number]}"
        end

        desc 'bye', 'say bye!'
        def bye
            puts "Bye! Call me at #{options[:number]}"
        end
    end

    class Root < Thor
        register CLI::Greet, 'greet', 'greet [COMMAND]', 'Greet with a command'        
        tasks["greet"].options = CLI::Greet.class_options
    end
end

CLI::Root.start

有了这个,ruby greet.rb help greet返回

Usage:
  greet.rb greet [COMMAND]

Options:
  [--number=NUMBER]  
                     # Default: 555-1212

Greet with a command

请注意,这里仍然需要一个技巧:tasks["greet"].options = CLI::Greet.class_options. 在 Thor 中也为此提交了CLI::Root一个错误。

于 2012-08-01T20:29:31.173 回答