Skip to content

Instantly share code, notes, and snippets.

@tiagopog
Last active July 12, 2018 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagopog/ddf4ba3766700026fa2ccc7acde2af16 to your computer and use it in GitHub Desktop.
Save tiagopog/ddf4ba3766700026fa2ccc7acde2af16 to your computer and use it in GitHub Desktop.
ActiveRecord - Outside Rails (microservice example)
class CreateFoo < ActiveRecord::Migration[5.0]
def change
create_table(:foos, force: true) do |t|
t.text :message, null: false
t.datetime :created_at, null: false
end
end
end
require 'active_record'
require 'erb'
namespace :db do
env = ENV['MICROSERVICE_ENV']
config = File
.read('config/database.yml')
.then(&ERB.method(:new))
.then(&:result)
.then(&YAML.method(:load))
.dig(env)
desc 'Create the database'
task :create do
admin_config = config.merge('database' => 'postgres', 'schema_search_path' => 'public')
ActiveRecord::Base.establish_connection(admin_config)
ActiveRecord::Base.connection.create_database(config['database'])
puts 'Database created.'
end
desc 'Migrate the database'
task :migrate do
ActiveRecord::Base.establish_connection(config)
ActiveRecord::Base.connection.migration_context.migrate
Rake::Task['db:schema'].invoke
puts 'Database migrated.'
end
desc 'Migrate the database'
task :rollback do
ActiveRecord::Base.establish_connection(config)
ActiveRecord::Base.connection.migration_context.rollback
Rake::Task['db:schema'].invoke
puts 'Last migration has been reverted.'
end
desc 'Drop the database'
task :drop do
admin_config = config.merge('database' => 'postgres', 'schema_search_path' => 'public')
ActiveRecord::Base.establish_connection(admin_config)
ActiveRecord::Base.connection.drop_database(config['database'])
puts 'Database deleted.'
end
desc '[Reset the database'
task reset: %i[drop create migrate]
desc 'Create a db/schema.rb file that is portable against any DB supported by AR'
task :schema do
require 'active_record/schema_dumper'
ActiveRecord::Base.establish_connection(config)
File.open('db/schema.rb', 'w:utf-8') do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
end
end
namespace :g do
desc 'Generate migration'
task :migration do
name = ARGV[1] || raise('Specify name: rake g:migration your_migration')
timestamp = Time.now.strftime("%Y%m%d%H%M%S")
path = File.expand_path("../../../db/migrate/#{timestamp}_#{name}.rb", __FILE__)
klass_name = name.split('_').map(&:capitalize).join
File.open(path, 'w') do |file|
file.write <<~EOF
class #{klass_name} < ActiveRecord::Migration[5.0]
def change
end
end
EOF
end
puts "Migration #{path} created"
abort
end
end
#!/usr/bin/env rake
require_relative './config/setup'
Dir['lib/tasks/**/*.rake'].each { |path| load path }
# Require external gems
require 'bundler/setup'
ROOT_DIR = File.expand_path("../", File.dirname(__FILE__)).freeze
CONFIG_DIR = File.join(ROOT_DIR, 'config').freeze
# Require environment & server config files
%w[environment server].each { |path| require File.join(CONFIG_DIR, path) }
Microservice::Env = Microservice::Config::Environment
# Microservice setup
module Microservice
module Config
module Setup
FILES = {
lib: Dir['lib/**/*.rb'].map { |path| path.gsub(/lib\//, '') },
initializers: Dir['config/initializers/**/*.rb']
}.freeze
module_function
def apply
update_load_path
require_bundled_gems
require_initializers
require_inner_lib_files
initialize_database
end
def update_load_path
lib_dir = File.join(ROOT_DIR, 'lib')
$LOAD_PATH.push(lib_dir) unless $LOAD_PATH.include?(lib_dir)
end
def require_bundled_gems
Bundler.require(:default, Microservice::Env.name)
end
def require_inner_lib_files
proto_files, other_files = FILES[:lib].partition { |path| path =~ /_pb.rb\z/ }
require_multiple(proto_files)
require_multiple(other_files)
end
def require_multiple(path_array)
path_array.each { |path| require path }
end
def require_initializers
FILES[:initializers].each { |path| require ['.', path].join('/') }
end
def initialize_database
ActiveRecord::Base.establish_connection(database_config)
end
def database_config
@database_config ||= File
.read('config/database.yml')
.then(&ERB.method(:new))
.then(&:result)
.then(&YAML.method(:load))
.dig(Microservice::Env.name)
end
end
end
end
Microservice::Config::Setup.apply
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment