Search code examples
ruby-on-railsrake

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?


Solution

  • 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