Using ActiveRecord outside Rails Part II

I previously posted about using ActiveRecord outside Rails last week. Since the post I’ve discovered a problem with the method when I rolled it out to my server (using the production environment) and read an excellent blog post on why that particular method is just plain WRONG!

I must admit the previous method did feel like it was a hack, and one of DHH’s goals with Rails is to encourage developers to do the right thing. Consequently, if you end up doing something that feels wrong because it is hard and/or ugly you should stop as there is probably an easier, Rails-esque way.

Rake

Rake, in the context of your Rails app, has everything you need to write a quick and DRY process that accepts arguments and can run all of your lovely tasks whenever you like.

By using rake we get access to all of the Rails application for free. So instead of loading Rails manually, a simple rake task can run any Ruby code in the application’s context.

HOWTO

Create a new file in lib/tasks with the extension .rake with your
required task:

desc 'example of a rake task'
task :my_task => :environment do
  # Your code goes here
end

To invoke it simply cd to your rails directory and run
rake with your task name (optionally specify the Rails environment).
The code inside the task will have full access to your Rails
environment including models.

cd /path/to/rails/application
rake <task_name> RAILS_ENV=production

You can check that the task is available by looking at the output of rake --tasks. (Any .rake files in the lib/tasks directory should be automatically included).

As a final note you could use this for scheduled tasks by running the above code via UNIX cron or a Windows scheduled task. I’ve updated my script from the previos method as a Rake task and it now works perfectly in production mode.

References

Script vs Rake…


About this entry