簡體   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