【问题标题】:Ruby - run Thor command without argumentRuby - 不带参数运行 Thor 命令
【发布时间】:2017-03-27 05:53:30
【问题描述】:

我必须使用这个命令来执行脚本:

$ruby file.rb keyword --format oneline --no-country-code --api-key=API

formatno-country-codeapi-keythor 选项。 keyword 是我方法中的参数:

class TwitterTrendReader < Thor
    method_option :'api-key', :required => true
    method_option :format
    method_option :'no-country-code', :type => :boolean

    def execute (keyword)
        #read file then display the results matching `keyword`
    end

default_task :execute
end

问题是keyword 是可选的,如果我运行没有keyword 的命令,脚本应该打印文件中的所有条目,否则,它只显示匹配keyword 的条目。

所以我有这个代码:

if ARGV.empty?
  TwitterTrendReader.start ''
else
  TwitterTrendReader.start ARGV
end

它仅在我指定keyword 但没有keyword 时才有效,我得到这个:

$ruby s3493188_p3.rb --api-key="abC9hsk9"
ERROR: "s3493188_p3.rb execute" was called with no arguments
Usage: "s3493188_p3.rb [keyword] --format oneline --no-country-code --api-key=API-KEY"

所以请告诉我我可以使参数可选的正确方法是什么。谢谢!

【问题讨论】:

    标签: ruby arguments thor


    【解决方案1】:

    您当前的 def execute (keyword) 实现是 1(也就是说,它声明了一个强制参数。)如果您希望能够省略它,请将该参数设为可选。

    改变

    def execute (keyword)
        #read file then display the results matching `keyword`
    end
    

    到:

    def execute (keyword = nil)
      if keyword.nil?
        # NO KEYWORD PASSED
      else
        # NORMAL PROCESSING
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多