Rake provide an easy to use task execution mechanism, but it also has some useful logic for extending existing tasks. Here are a few examples of the kinds of Rake tasks I've been using to make my life easier.
Chaining Tasks
It's possible for one task to call another, but it's also possible for this to go between namespaces:
namespace :db do
task :environment => :environment do
puts "db:environment"
end
task :migrate => :environment do
puts "db:migrate"
end
end
task :environment do
puts "environment"
end
Running $ rake db:environment
will invoke both the db:environment
and environment
tasks.
We use this to integrate with other task libraries, e.g. ActiveRecord.
Stateful Tasks
Sometimes it's useful to have stateful tasks:
LOGGER = Logger.new
task :verbose do
LOGGER.level = Logger::DEBUG
end
task :deploy do
LOGGER.debug(:environment){ENV}
# ...
end
# invoke as rake verbose deploy
Running $ rake verbose deploy
will print out more detailed information.
We use this when running tasks as background jobs - verbose is not defined unless we want extra output for debugging.
Stateful Pipelines
You can use this to make flexible filters and tasks which can be configured to do different things:
namespace :dump do
task :users do
@records = Users.all
end
task :posts do
@records = Posts.all
end
task :updated_recently do
@records = @records.where("updated_at > ?", 6.months.ago)
end
task :as_json do
$stdout.write(@records.as_json)
end
task :as_xml do
$stdout.write(@records.as_xml)
end
end
We use tasks like these to export data for customers - we almost always have some specific requirements - but we can usually chain together a set of existing tasks to get the desired output.
Multiple Tasks
It's possible to define multiple tasks with the same name. This is useful if you want to combine multiple files containing tasks
task :deploy do
puts "Deploy 1"
end
task :deploy do
puts "Deploy 2"
end
Running $ rake deploy
will invoke both tasks.
We use this to keep our .rake
files simple, focused and organised.
Comments
Leave a comment
Please note, comments must be formatted using Markdown. Links can be enclosed in angle brackets, e.g.
<www.codeotaku.com>
.