如何使用 OptionParser 解析 rake 参数 [英] How to parse rake arguments with OptionParser

查看:38
本文介绍了如何使用 OptionParser 解析 rake 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用该答案 我试图使用 OptionParser 来解析 rake 参数.我从那里简化了示例,我不得不添加两个 ARGV.shift 以使其工作.

Reffering that answer I was trying to use OptionParser to parse rake arguments. I simplified example from there and I had to add two ARGV.shift to make it work.

require 'optparse'

namespace :user do |args|

  # Fix I hate to have here
  puts "ARGV: #{ARGV}"
  ARGV.shift
  ARGV.shift
  puts "ARGV: #{ARGV}"

  desc 'Creates user account with given credentials: rake user:create'
  # environment is required to have access to Rails models
  task :create => :environment do
    options = {}
    OptionParser.new(args) do |opts|      
      opts.banner = "Usage: rake user:create [options]"
      opts.on("-u", "--user {username}","Username") { |user| options[:user] = user }
    end.parse!

    puts "user: #{options[:user]}"

    exit 0
  end
end

这是输出:

$ rake user:create -- -u foo
ARGV: ["user:create", "--", "-u", "foo"]
ARGV: ["-u", "foo"]
user: foo

我认为 ARGV.shift 不是应该做的方式.我想知道为什么没有它就不能工作以及如何以适当的方式修复它.

I assume ARGV.shift is not the way it should be done. I would like to know why it doesn't work without it and how to fix it in a proper way.

推荐答案

您可以使用方法 OptionParser#order! 返回 ARGV 且没有错误参数:

You can use the method OptionParser#order! which returns ARGV without the wrong arguments:

options = {}

o = OptionParser.new

o.banner = "Usage: rake user:create [options]"
o.on("-u NAME", "--user NAME") { |username|
  options[:user] = username
}
args = o.order!(ARGV) {}
o.parse!(args)
puts "user: #{options[:user]}"

你可以像这样传递参数:$ rake foo:bar -- '--user=john'

You can pass args like that: $ rake foo:bar -- '--user=john'

这篇关于如何使用 OptionParser 解析 rake 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆