如何使用OptionParser解析rake参数

时间:2015-01-23 12:52:54

标签: ruby-on-rails ruby rake rake-task

Reffering that answer我试图使用OptionParser来解析rake个参数。我从那里简化了示例,我必须添加两个ARGV.shift才能使其正常工作。

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不是应该做的。我想知道为什么没有它以及如何以正确的方式解决它不起作用。

4 个答案:

答案 0 :(得分:6)

您可以使用返回ARGV的方法OptionParser#order!,而不使用错误的参数:

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]}"

你可以传递这样的args:$ rake foo:bar -- '--user=john'

答案 1 :(得分:3)

我知道这并没有严格回答你的问题,但是你考虑过使用任务参数吗?

这样你就可以摆脱OptionParserARGV

namespace :user do |args|
  desc 'Creates user account with given credentials: rake user:create'
  task :create, [:username] => :environment do |t, args|
    # when called with rake user:create[foo],
    # args is now {username: 'foo'} and you can access it with args[:username]
  end
end

有关详细信息,请参阅this answer here on SO

答案 2 :(得分:0)



#determines if file exists
if  [ -f  * ]; then 
    echo "File found"
else 
    echo "File not Found"
fi  

# returns file to array
#Needs name still
NewFiles[0] = 

#output what what found in 0 index
echo "Found File"
echo NewFiles[0]




一个澄清的例子:

alther tips Gist

https://gist.github.com/altherlex/bb67f17cb8eefb281866fc21dfeb921a

答案 3 :(得分:-1)

您必须在-ufoo之间加上'=':

$ rake user:create -- -u=foo

而不是:

$ rake user:create -- -u foo