Hack: Redefine a rails model for a rake task
Well, this is weird.
I wrote a rake task to import data from a csv file (output from a legacy system) into my development database for testing. The catch was that I wanted to extend my model class by adding a custom method only in the rake file.
require File.expand_path(File.dirname(__FILE__) + "/../../config/environment") class Customer < ActiveRecord::Base def my_custom_method end end
But here, for some reason, rake tries to define a _new_ activerecord model, not redefine the existing model I’ve written. So, what I tried was to precede the class definition with:
c = Customer.new # which really goes to waste
and it worked ! Rake now recognizes that I’m trying to add a method to my existing rails model !

Leave a Comment