2016-07-05 16 views
0

我有一個工具,我更新,需要有一個參數需要另一種說法,例如:當這個運行你如何使用optparse有一個標誌參數需要另一種說法

require 'optparse' 

OPTIONS = {} 

OptionParser.new do |opts| 
    opts.on('-t', '--type INPUT', String, 'Verify a type'){ |o| OPTIONS[:type] = o } 
end.parse! 

def help_page 
    puts 'ruby test.rb -t dev' 
end 

def gather_type 
    case OPTIONS[:type] 
    when /dev/ 
    unlock(OPTIONS[:type]) 
    else 
    help_page 
    end 
end 

def unlock(type) 
    if type == 'unlock' #Find out what type by passing argument another argument 
    puts 'Unlock account' 
    else 
    puts 'Reset account' 
    end 
end 

def start 
    case 
    when OPTIONS[:type] 
    gather_type 
    else 
    help_page 
    end 
end 

start 

以下內容:

C:\Users\bin\ruby>ruby test.rb -t dev=unlock 
Reset account 
C:\Users\bin\ruby>ruby test.rb -t dev=reset 
Reset account 

現在,一切都很好,很正常,但我想要做的就是給dev部分參數,並從那裏來決定,如果它是一個解鎖或者如果它是一個復位:

ruby test.rb -t dev=unlock OR ruby test.rb -t dev=reset

後,我希望unlock(type)方法來確定給予了flags參數和輸出正確的信息是什麼參數,所以

C:\Users\bin\ruby>ruby test.rb -t dev=unlock 
Unlock account 

C:\Users\bin\ruby>ruby test.rb -t dev=reset 
Reset account 

我該如何去確定一個參數是給予國旗的論據?

回答

0

我想通了,如果你把在括號內的選項,你可以得到什麼,我問:

require 'optparse' 

OPTIONS = {} 

OptionParser.new do |opts| 
    opts.on('-t', '--type INPUT[=INPUT]', String, 'Verify a type'){ |o| OPTIONS[:type] = o } 
end.parse! 

def help_page 
    puts 'ruby test.rb -t dev' 
end 

def gather_type 
    case OPTIONS[:type] 
    when /dev/ 
    unlock(OPTIONS[:type]) 
    else 
    help_page 
    end 
end 

def unlock(type) 
    if type =~ /unlock/ #Find out what type by passing argument another argument 
    puts 'Unlock account' 
    elsif type =~ /reset/ 
    puts 'Reset account' 
    else 
    puts 'No flag given defaulting to unlock' 
    end 
end 

def start 
    case 
    when OPTIONS[:type] 
    gather_type 
    else 
    help_page 
    end 
end 

start 


C:\Users\bin\ruby>ruby test.rb -t dev 
No flag given defaulting to unlock 

C:\Users\bin\ruby>ruby test.rb -t dev=unlock 
Unlock account 

C:\Users\bin\ruby>ruby test.rb -t dev=reset 
Reset account 
相關問題