How to pass command line arguments to a rake task

后端 未结 19 2150
走了就别回头了
走了就别回头了 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:38

    I like the "querystring" syntax for argument passing, especially when there are a lot of arguments to be passed.

    Example:

    rake "mytask[width=10&height=20]"
    

    The "querystring" being:

    width=10&height=20
    

    Warning: note that the syntax is rake "mytask[foo=bar]" and NOT rake mytask["foo=bar"]

    When parsed inside the rake task using Rack::Utils.parse_nested_query , we get a Hash:

    => {"width"=>"10", "height"=>"20"}
    

    (The cool thing is that you can pass hashes and arrays, more below)

    This is how to achieve this:

    require 'rack/utils'
    
    task :mytask, :args_expr do |t,args|
      args.with_defaults(:args_expr => "width=10&height=10")
      options = Rack::Utils.parse_nested_query(args[:args_expr])
    end
    

    Here's a more extended example that I'm using with Rails in my delayed_job_active_record_threaded gem:

    bundle exec rake "dj:start[ebooks[workers_number]=16&ebooks[worker_timeout]=60&albums[workers_number]=32&albums[worker_timeout]=120]"
    

    Parsed the same way as above, with an environment dependency (in order load the Rails environment)

    namespace :dj do
      task :start, [ :args_expr ] => :environment do |t, args|
        # defaults here...
        options = Rack::Utils.parse_nested_query(args[:args_expr])  
      end
    end
    

    Gives the following in options

    => {"ebooks"=>{"workers_number"=>"16", "worker_timeout"=>"60"}, "albums"=>{"workers_number"=>"32", "worker_timeout"=>"120"}}
    

提交回复
热议问题