Ruby - 没有参数运行Thor命令

时间:2017-03-27 05:53:30

标签: ruby arguments thor

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

$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的命令,脚本应该打印文件中的所有条目,否则,它只显示与{{1}匹配的条目}}

所以我有这段代码:

keyword

仅当我指定if ARGV.empty? TwitterTrendReader.start '' else TwitterTrendReader.start ARGV end 但没有keyword时,它才有用,我明白了:

keyword

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

1 个答案:

答案 0 :(得分:1)

您当前的def execute (keyword)实现是arity 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
相关问题