How to pass command line arguments to a rake task

后端 未结 19 2144
走了就别回头了
走了就别回头了 2020-11-22 10:13

I have a rake task that needs to insert a value into multiple databases.

I\'d like to pass this value into the rake task from the command line, or from another

19条回答
  •  迷失自我
    2020-11-22 10:54

    If you want to pass named arguments (e.g. with standard OptionParser) you could use something like this:

    $ rake user:create -- --user test@example.com --pass 123
    

    note the --, that's necessary for bypassing standard Rake arguments. Should work with Rake 0.9.x, <= 10.3.x.

    Newer Rake has changed its parsing of --, and now you have to make sure it's not passed to the OptionParser#parse method, for example with parser.parse!(ARGV[2..-1])

    require 'rake'
    require 'optparse'
    # Rake task for creating an account
    
    namespace :user do |args|
      desc 'Creates user account with given credentials: rake user:create'
      # environment is required to have access to Rails models
      task :create do
        options = {}
        OptionParser.new(args) do |opts|
          opts.banner = "Usage: rake user:create [options]"
          opts.on("-u", "--user {username}","User's email address", String) do |user|
            options[:user] = user
          end
          opts.on("-p", "--pass {password}","User's password", String) do |pass|
            options[:pass] = pass
          end
        end.parse!
    
        puts "creating user account..."
        u = Hash.new
        u[:email] = options[:user]
        u[:password] = options[:pass]
        # with some DB layer like ActiveRecord:
        # user = User.new(u); user.save!
        puts "user: " + u.to_s
        puts "account created."
        exit 0
      end
    end
    

    exit at the end will make sure that the extra arguments won't be interpreted as Rake task.

    Also the shortcut for arguments should work:

     rake user:create -- -u test@example.com -p 123
    

    When rake scripts look like this, maybe it's time to look for another tool that would allow this just out of box.

提交回复
热议问题