While I Pondered…

Over many a quaint and curious volume of forgotten lore.

Rake calling models with arguments December 21, 2009

Filed under: Uncategorized — masonoise @ 8:28 pm
Tags: ,

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)
        Themodel.load_csv(args.file_path)
      else
        puts "Must specify a file for importing"
      end
    end
  end

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.

 

 
Follow

Get every new post delivered to your Inbox.