Executing methods of Rails controllers in Rake tasks
Table of Contents for Ruby on Rails progression
- A noob and Ruby on Rails 2
- SEO Tools, my first Ruby on Rails application
- Foreign relations in RoR models and forms
- File uploading in RoR
- Posting with the Ruby HTTPClient
- Executing methods of Rails controllers in Rake tasks
- Securing a Ruby on Rails app
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