Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 891
NJ. Avatar asked Mar 05 '11 23:03

NJ.


People also ask

What are Rake tasks for?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.

How do you call a rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.


1 Answers

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
like image 113
aceofspades Avatar answered Sep 24 '22 01:09

aceofspades