如何让Thor显示选项?

时间:2012-08-01 13:47:44

标签: ruby gem thor

这是我的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

1 个答案:

答案 0 :(得分:7)

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

ruby greet.rb greet help hi

你得到了

Usage:
  greet.rb hi

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

Say hi!

哪个,是的,是错的 - 它在帮助中没有子命令。在托尔有一个bug申请。但是,它正确地显示了方法选项。

然而,您正在寻找的是一种类方法。这是为整个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中的CLI::Root行。还有一个bug在托尔也提出了这个问题。