How can I load ActiveRecord database tasks on a Ruby project outside Rails?

The easiest thing to do is to load the tasks already defined in databases.rake. Here is a GIST of how it was done.

Inspired by this GIST by Drogus

Rakefile.rb

require 'yaml'
require 'logger'
require 'active_record'

include ActiveRecord::Tasks

class Seeder
  def initialize(seed_file)
    @seed_file = seed_file
  end

  def load_seed
    raise "Seed file '#{@seed_file}' does not exist" unless File.file?(@seed_file)
    load @seed_file
  end
end


root = File.expand_path '..', __FILE__
DatabaseTasks.env = ENV['ENV'] || 'development'
DatabaseTasks.database_configuration = YAML.load(File.read(File.join(root, 'config/database.yml')))
DatabaseTasks.db_dir = File.join root, 'db'
DatabaseTasks.fixtures_path = File.join root, 'test/fixtures'
DatabaseTasks.migrations_paths = [File.join(root, 'db/migrate')]
DatabaseTasks.seed_loader = Seeder.new File.join root, 'db/seeds.rb'
DatabaseTasks.root = root

task :environment do
  ActiveRecord::Base.configurations = DatabaseTasks.database_configuration
  ActiveRecord::Base.establish_connection DatabaseTasks.env.to_sym
end

load 'active_record/railties/databases.rake'

For Rails 3.x:

You need to manually create the tasks. As example here is how to add them (this example uses the environment variables like Rails):

  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

and you'll have the task rake db:recreate available

For Rails 4.x:

If you want to have the ActiveRecord rake tasks available in your ruby app, take a look at the documentation.

Example usage of DatabaseTasks outside Rails could look as such:

include ActiveRecord::Tasks
DatabaseTasks.database_configuration = YAML.load(File.read('my_database_config.yml'))
DatabaseTasks.db_dir = 'db'
# other settings...

DatabaseTasks.create_current('production')

Also you have here an example on how to use ActiveRecord in your ruby aplication.


You could try the standalone-migrations gem: https://github.com/thuss/standalone-migrations