【问题标题】:Thor - command line option not recognized in methodThor - 方法中无法识别命令行选项
【发布时间】:2017-03-26 23:28:06
【问题描述】:

我必须使用这个命令来运行我的ruby 程序:

$ruby filename.rb NAME --from="People" --yell

我有这样的脚本:

require 'thor'

class CLI < Thor
  desc "hello NAME", "say hello to NAME"

  method_option :from, :required => true
  method_option :yell, :type => :boolean
  def self.hello(name)
    output = []
    output << "from: #{options[:from]}" if options[:from]
    output << "Hello #{name}"
    output = output.join("\n")
    puts options[:yell] ? output.upcase : output
  end
end

CLI.hello(ARGV)

当我运行代码时,我得到以下输出:

c:\RubyWorkplace\Assignment1>ruby testing.rb Jay --from="Ray"
FROM: #<THOR::OPTION:0X000000031D7998>
HELLO ["JAY", "--FROM=RAY"]

c:\RubyWorkplace\Assignment1>ruby testing.rb Jay --from="Ray" --yell
FROM: #<THOR::OPTION:0X0000000321E528>
HELLO ["JAY", "--FROM=RAY", "--YELL"]

看起来:yell无论我指定与否总是有效,并且optionshello方法中都被读取为name输入。

我从在线教程中找到并尝试了很多方法,但问题没有解决。请告诉我出了什么问题。谢谢!

【问题讨论】:

    标签: ruby thor


    【解决方案1】:

    问题是由于我在脚本中调用CLI.hello ARGV 引起的。程序运行时会调用hello方法,并将所有命令行输入识别为hello的参数,是一个数组。

    解决此问题的方法之一是通过删除self 公开hello,通过start 方法调用脚本。

    require 'thor'
    
    class CLI < Thor
      desc "hello NAME", "say hello to NAME"
    
      method_option :from, :required => true
      method_option :yell, :type => :boolean
      def hello(name)
        #do something
      end
    end
    
    CLI.start ARGV
    

    【讨论】:

      最近更新 更多