20

I have a rake task that I want to pass parameters to. For example, I want to issue a command like

<prompt> rake db:do_something 1

and inside the rake task:

...
cust = Customer.find( the_id_passed_in )
# do something with this customer record, etc...
...

Pretty straightforward, right?

NJ.
  • 2,155
  • 6
  • 26
  • 35
  • 2
    possible duplicate of [How do I pass command line arguments to a rake task?](http://stackoverflow.com/questions/825748/how-do-i-pass-command-line-arguments-to-a-rake-task) – Ken White Feb 28 '14 at 01:10

2 Answers2

38

The way rake commands accept and define arguments is, well, not pretty.

Call your task this way:

<prompt> rake db:do_something[1,2]

I've added a second parameter to show that you'll need the comma, but omit any spaces.

And define it like this:

task :do_something, :arg1, :arg2 do |t, args|
  args.with_defaults(:arg1 => "default_arg1_value", :arg2 => "default_arg2_value")
  # args[:arg1] and args[:arg2] contain the arg values, subject to the defaults
end
Jirapong
  • 24,074
  • 10
  • 54
  • 72
aceofspades
  • 7,568
  • 1
  • 35
  • 48
  • 1
    how do you do this with a task that requires the rails environment to be loaded? e.g. normally `task :do_something => :environment do` – Duke May 01 '13 at 20:50
  • 10
    `task :do_something, [:arg1, :arg2] => :environment do |t, args|` – Duke May 01 '13 at 20:55
0

While passing parameters, it is better option is an input file, can this be a excel a json or whatever you need and from there read the data structure and variables you need from that including the variable name as is the need. To read a file can have the following structure.

  namespace :name_sapace_task do
    desc "Description task...."
      task :name_task  => :environment do
        data =  ActiveSupport::JSON.decode(File.read(Rails.root+"public/file.json")) if defined?(data)
    # and work whit yoour data, example is data["user_id"]

    end
  end

Example json

{
  "name_task": "I'm a task",
  "user_id": 389,
  "users_assigned": [389,672,524],
  "task_id": 3
}

Execution

rake :name_task 
Kara
  • 6,115
  • 16
  • 50
  • 57
  • 1
    Why do you give [two identical answers](http://stackoverflow.com/a/22070576/861716)? It's better to answer one question and mark the other as duplicate. – Gert Arnold Feb 27 '14 at 22:58