简体   繁体   English

Ruby-不带参数运行Thor命令

[英]Ruby - run Thor command without argument

I have to use this command to execute the script: 我必须使用此命令来执行脚本:

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

Where, the format , no-country-code , api-key are thor options. 其中,该formatno-country-codeapi-keythor的选择。 The keyword is the argument in my method: 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

The problem is the keyword is optional, if I run the command without the keyword , the script should print all entries in the file, otherwise, it only display the entries matching the keyword . 问题是keyword是可选的,如果我在不使用keyword情况下运行命令,脚本将打印文件中的所有条目,否则,它将仅显示与keyword匹配的条目。

so I have this code: 所以我有这段代码:

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

It only works when I specify a keyword but without keyword , I get this: 它只能当我指定一个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"

So please tell me what is the proper way that I could make the argument optional. 因此,请告诉我使参数可选的正确方法是什么。 Thank you! 谢谢!

Your current implementation of def execute (keyword) is of arity 1 (that said, it declares one mandatory parameter.) Make the parameter optional, if you want to have an ability to omit it. 您当前的def execute (keyword)的含义为1 (也就是说,它声明了一个强制性参数。)如果希望能够省略该参数,则使该参数为可选。

Change 更改

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

to: 至:

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