繁体   English   中英

Ruby-不带参数运行Thor命令

[英]Ruby - run Thor command without argument

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

$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"

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

您当前的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM