How to pass command line arguments to a rake task

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

    I've found the answer from these two websites: Net Maniac and Aimred.

    You need to have version > 0.8 of rake to use this technique

    The normal rake task description is this:

    desc 'Task Description'
    task :task_name => [:depends_on_taskA, :depends_on_taskB] do
      #interesting things
    end
    

    To pass arguments, do three things:

    1. Add the argument names after the task name, separated by commas.
    2. Put the dependencies at the end using :needs => [...]
    3. Place |t, args| after the do. (t is the object for this task)

    To access the arguments in the script, use args.arg_name

    desc 'Takes arguments task'
    task :task_name, :display_value, :display_times, :needs => [:depends_on_taskA, :depends_on_taskB] do |t, args|
      args.display_times.to_i.times do
        puts args.display_value
      end
    end
    

    To call this task from the command line, pass it the arguments in []s

    rake task_name['Hello',4]
    

    will output

    Hello
    Hello
    Hello
    Hello
    

    and if you want to call this task from another task, and pass it arguments, use invoke

    task :caller do
      puts 'In Caller'
      Rake::Task[:task_name].invoke('hi',2)
    end
    

    then the command

    rake caller
    

    will output

    In Caller
    hi
    hi
    

    I haven't found a way to pass arguments as part of a dependency, as the following code breaks:

    task :caller => :task_name['hi',2]' do
       puts 'In Caller'
    end
    

提交回复
热议问题