You can use rake to automate all kinds of tasks. And of course, Rails takes advantage of it in a big way. Last summer I automated a few tasks by adding files to the ‘script’ directory. I thought I was being clever by doing a ‘require’ on ‘environment.rb’ and accessing my models that way.
Like many things in Rails, it’s even easier if you do it right! You can just list ”:environment” as a dependency in a rake task. Because rake handles the dependencies for you, you can string multiple tasks together and they will be aware of what has already been loaded. You have a connection to the database, and you can pass parameters such as RAILS_ENV=production.
With Rails 1.0, you can make custom tasks in the “lib/tasks” folder. As long as the filename ends with .rake, it will be available along with all the built-in tasks. You can see these by typing
Here’s an example from my Mint plugin that parses my webserver’s logs and inserts them into the Mint table:
desc "Read access logs and save to mint_visit table" task :mint_parse_logs => :environment do Mint.parse_log_file end
I realized that this was taking too many resources and the process would be killed by the shared server before it was done. Since I was only tracking hits to XML resources, I made a task to filter this out.
desc "Filter today's log" task :filter_httpd_log do system "grep xml today.log > filtered.log" end
The final solution was to make a task that runs both of these as dependencies:
desc "Filter and parse logs" task :filter_and_parse => [:filter_httpd_log, :mint_parse_logs]
I have cron setup to run certain scripts at intervals. Here’s what those look like:
# The output of "crontab -l" @daily /home/topfunky/bin/daily # My daily script cd /home/topfunky/mysite.com rake filter_and_parse RAILS_ENV=production
And that’s all there is to it. There are many things that can go wrong, like adjusting your Mint settings so most of your stats are wiped out. But that’s a different topic!
Rake can do so much more, but those are the basics. I’ll never write a solo Ruby script to work with my Rails apps…rake is the way to go.