Tag Archives: rake

A quick one here, since I had to search around and combine suggestions from a couple of places I found… I needed to write a rake task that would call a class method on one of the models, plus accept a command-line argument which it would pass on. The magical incantation that worked looks like this:

  namespace :mytest do
    desc "Import a CSV file into the database"
    task :import_csv, :file_path, :needs => [:environment] do |t, args|
      if (args.file_path)
        puts "Must specify a file for importing"

The trick was putting the argument :file_path followed by the :needs => [:environment] in order to get access to the model. At that point I could invoke the method on the model, and have access to args.file_path to pass into it.

Then it’s just a matter of invoking the task:

    rake mytest:import_csv[myfilepath.csv]

And there you go. Hope the info helps someone out.