How to parse rake arguments with OptionParser

前端 未结 4 506
情书的邮戳
情书的邮戳 2021-01-18 00:05

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.shi

相关标签:
4条回答
  • 2021-01-18 00:27

    Try this:

    require 'optparse'
    
    namespace :programs do |args|
      desc "Download whatever"
      task :download => [:environment] do
    
        # USAGE: rake programs:download -- rm
        #-- Setting options $ rake programs:download -- --rm
        options = {}
        option_parser = OptionParser.new
        option_parser.banner = "Usage: rake programs:download -- rm"
        option_parser.on("-r", "--rm","Remove s3 files downloaded") do |value|
          options[:remove] = value
        end
        args = option_parser.order!(ARGV) {}
        option_parser.parse!(args)
        #-- end
    
        # your code here
      end
    end
    
    0 讨论(0)
  • 2021-01-18 00:33

    I know this does not strictly answer your question, but did you consider using task arguments?

    That would free you having to fiddle with OptionParser and ARGV:

    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
    

    For more info, see this answer here on SO.

    0 讨论(0)
  • 2021-01-18 00:39

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

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

    0 讨论(0)
  • 2021-01-18 00:46

    You have to put a '=' between -u and foo:

    $ rake user:create -- -u=foo

    Instead of:

    $ rake user:create -- -u foo

    0 讨论(0)
提交回复
热议问题