Executing methods of Rails controllers in Rake tasks

I just found myself in need of a cron job that needed to call the same code that a Rails action view is calling in an ApplicationController.

After some googling I found the best article on the subject from Joyent: How to run a rake task from cron.

Below is pretty much a rehash of that article with a few gotchas I managed to sort out that it doesn’t cover.

Here is my push.rake in the lib/tasks folder:

namespace :push do
  desc "Push articles"
  task(:pusharticles => :environment){ p WpArticlesController.new.push_random_cron  }
end

Note the .new. there. This is needed since we’re calling instance methods. Push_random_cron is calling another instance method, thus defining it as a static method to avoid creating an instance will only lead to misery.

And this is my rake call to run the rake task:

rake RAILS_ENV=development push:pusharticles

Note development there. I’m not in production yet…

And finally the cron job entry:

cd /home/henrik/rails_projects/articlepusher && rake RAILS_ENV=development push:pusharticles


Related Posts

Tags: , , ,