2016-07-05 1 views
0

J'ai un outil que je mise à jour et la nécessité d'avoir un argument nécessite un autre argument, par exemple:Comment utiliser optparse d'avoir un argument flags nécessite un autre argument

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 

Lorsque cela est exécuté, vous obtenez les éléments suivants:

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

maintenant que tout est bien et dandy, mais ce que je veux faire est de donner à la partie dev un argument et aller de là pour décider si elle est un déverrouillage ou si elle est une remise à zéro:

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

Après que je veux la méthode unlock(type) pour déterminer quel argument a été donné à l'argument des drapeaux et de sortie les informations correctes, donc

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

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

Comment puis-je aller sur le point de déterminer si un argument était donné à l'argument du drapeau?

Répondre

0

je me suis dit que si vous mettez un choix entre parenthèses, vous pouvez obtenir ce que je demande:

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