< Ruby on Rails < Built-In Rails Tools

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
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.