Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

ActiveRecord 3.2.14

I want to use ActiveRecord in a non-Rails Ruby project. I want to have available the rake tasks that are defined by ActiveRecord. How can I do that?

rake db:create           # Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)
rake db:drop             # Drops the database using DATABASE_URL or the current Rails.env (use db:drop:all to drop all databases)
rake db:fixtures:load    # Load fixtures into the current environment's database
rake db:migrate          # Migrate the database (options: VERSION=x, VERBOSE=false)
rake db:migrate:status   # Display status of migrations
rake db:rollback         # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:dump      # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load      # Load a schema.rb file into the database
rake db:seed             # Load the seed data from db/seeds.rb
rake db:setup            # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)
rake db:structure:dump   # Dump the database structure to db/structure.sql
rake db:version          # Retrieves the current schema version number

The above list is the list of tasks that I want to be able to use on my non-Rails Ruby project that uses ActiveRecord. What do I have to write in my Rakefile?

Thanks in advance

like image 744
p.matsinopoulos Avatar asked Oct 06 '13 08:10

p.matsinopoulos


1 Answers

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'
like image 64
Jason Avatar answered Oct 06 '22 15:10

Jason