NJ.
NJ.

Reputation: 2175

Passing a parameter or two to a Rake task

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?

Upvotes: 20

Views: 10199

Answers (2)

aceofspades
aceofspades

Reputation: 7586

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

Upvotes: 38

tundervirld
tundervirld

Reputation: 11

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 

Upvotes: 0

Related Questions