Ruby on Rails/Built-In Rails Tools/Make your own rake tasks

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Built-In Rails Tools/Convenient Rake tasks Index Next: Built-In Rails Tools/Command-Line Reference

You can make your own rake task by creating a file in the lib/tasks directory of your Rails application and adding the Rake tasks to it. For example, adding the following to lib/tasks/database.rake will make the db:recreate task available to your Rails application:

  namespace :db do
    desc "Drop and create the current database"
    task :recreate => :environment do
      abcs = ActiveRecord::Base.configurations
      ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
      ActiveRecord::Base.connection.recreate_database(ActiveRecord::Base.connection.current_database)
    end
  end

The namespace method puts the contents of the block in the specified namespace. You can nest namespaces as deep as you want although usually one or two nestings is sufficient.

This task can now be executed with

rake db:recreate