简体   繁体   中英

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. The keyword is the argument in my method:

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 .

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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