Monday, December 17, 2007

Custom Rake tasks

Writing your own custom Rake task is very simple and almost not worthy of a blog post, but I can't remember everything, so it's here for reference.

In your lib/tasks directory create a file with the extension .rake. i.e. print.rake.

namespace :print do
task :one do
attention "One"
end

task :two do
attention "Two"
end

task :three do
attention "Three"
end

task :first_user => :environment do
puts User.find(1).first_name
end

task :all => [:one, :two, :three]

def attention(msg)
puts "!!!!!!!!!! #{msg}"
end
end

#Sample Calls

rake print:three
!!!!!!!!!! "Three"

rake print:all
!!!!!!!!!! "One"
!!!!!!!!!! "Two"
!!!!!!!!!! "Three"
  • Wrap tasks in the namespace block to namespace your tasks.
    • then call by <namespace>:<task_name>
  • Using => in your task declaration denotes a dependency.
  • Use an array for multiple dependencies (i.e. the :all task)
  • The :environment dependency will load the Rails environment
    • :first_user task
  • You don't need the block if the task is empty.
    • the print:all task - no do..end defined
  • You can define standard methods for code reuse.
    • the attention method

0 comments: