ActiveRecord criar, descartar e migrações sem Rails

Aqui está uma tarefa de criação, eliminação e migração do Active Record (> 5) sem trilhos baseada no artigo de Wes Bailey .

criado por: charly-palencia & Erlinis
Detalhes:
* Somente banco de dados PostgreSQL

database_connection.rb

require 'active_record'
require 'erb'

module DatabaseConnection
def self.connect!(env)
#Ref https://github.com/puma/puma#clustered-mode
ActiveSupport.on_load(:active_record) do
::ActiveRecord::Base.connection_pool.disconnect! if ::ActiveRecord::Base.connected?
::ActiveRecord::Base.configurations = YAML.load(ERB.new(File.read("db/config.yml")).result) || {}
config
= ::ActiveRecord::Base.configurations[env.to_s]
::ActiveRecord::Base.establish_connection(config)
end
end
end

tarefas / banco de dados.rb

require 'yaml'
require 'config/database_connection'
require 'active_record'

namespace :db do

task
:environment do
path
= File.join(File.dirname(__FILE__), '../db/migrate')
migrations_paths
= [path]
DATABASE_ENV
= ENV['RACK_ENV'] || 'development'
MIGRATIONS_DIR
= ENV['MIGRATIONS_DIR'] || migrations_paths
end

task
:configuration => :environment do
@config = YAML.load(ERB.new(File.read("db/config.yml")).result)[DATABASE_ENV]
end

task
:configure_connection => :configuration do
DatabaseConnection.connect!(DATABASE_ENV)
ActiveRecord::Base.logger = Logger.new STDOUT if @config['logger']
end

desc
'Create the database from db/config.yml for the current DATABASE_ENV'
task
:create => :configure_connection do
database
= ActiveRecord::Tasks::PostgreSQLDatabaseTasks.new(@config)
database
.create
puts
"Database created"
end

desc
'Drops the database for the current DATABASE_ENV'
task
:drop => :configure_connection do
database
= ActiveRecord::Tasks::PostgreSQLDatabaseTasks.new(@config)
database
.drop
puts
"Database dropped"
end

desc
'Migrate the database (options: VERSION=x, VERBOSE=false).'
task
:migrate => :configure_connection do
begin
verbose
= ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
version
= ENV["VERSION"] ? ENV["VERSION"].to_i : nil
scope
= ENV['SCOPE']
verbose_was
, ActiveRecord::Migration.verbose = ActiveRecord::Migration.verbose, verbose
ActiveRecord::Migrator.migrate(MIGRATIONS_DIR, version) do |migration|
scope
.blank? || scope == migration.scope
end
ActiveRecord::Base.clear_cache!
ensure
ActiveRecord::Migration.verbose = verbose_was
end
end

desc
'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
task
:rollback => :configure_connection do
step
= ENV['STEP'] ? ENV['STEP'].to_i : 1
ActiveRecord::Migrator.rollback(MIGRATIONS_DIR, step)
end