如何使用optparse来拥有flags参数需要另一个参数

时间:2016-07-05 17:50:10

标签: ruby 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部分一个参数并从那里开始判断它是否解锁或者它是否已解锁。 sa重置:

ruby test.rb -t dev=unlockruby 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

我怎样才能确定是否对该旗帜的参数给出了论证?

1 个答案:

答案 0 :(得分: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
相关问题