2017-03-27 3 views
0

없이 실행 토르 명령 :루비 - 내가 스크립트를 실행하려면이 명령을 사용할 필요가 인수

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

format, no-country-code, api-keythor 옵션입니다. 그렇지 않으면 항목 만 표시

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 내 방식의 인수입니다 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" 

그래서 적절한 방법이 무엇인지 말해하시기 바랍니다 나는 인수를 선택적으로 만들 수있다. 고맙습니다!

답변

1

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 
+0

이 크게 작동합니다. 정말 고맙습니다! –

관련 문제