Skip to content

Instantly share code, notes, and snippets.

@spikeheap
Last active January 2, 2017 19:45
Show Gist options
  • Save spikeheap/e7659f3c1d84557539d72576ce7e9ddc to your computer and use it in GitHub Desktop.
Save spikeheap/e7659f3c1d84557539d72576ce7e9ddc to your computer and use it in GitHub Desktop.
Rails Docker DB with migrations
#/config/environments/test.rb
require 'docker'
Rails.application.configure do
config.after_initialize do
logger.info "db:migrate"
ActiveRecord::Migrator.migrate(Rails.root.join("db/migrate"), nil)
end
config.before_initialize do
# set this to something other than 'postgres'
DB_NAME='myProject'
def try_psql(container)
ret = container.exec(["psql", "-U", "postgres", "-c", "SELECT 1"], wait: 10, tty: true)
raise 'No PSQL SELECT 1' unless ret[2] == 0
end
def retry_psql(container)
tries ||= 10
print "."
try_psql(container)
rescue Exception => e
sleep 1
retry unless (tries -= 1).zero?
else
puts " success (attempt #{11-tries}/10)"
# just hold off for a couple of seconds as the docker init process brings the database up and down a few times at startup.
sleep 2
end
if( ENV['DOCKER_DB'] )
container = Docker::Container.create( 'Image' => 'postgres:latest', 'ExposedPorts' => { '5432/tcp' => {} },
'HostConfig' => {
'PortBindings' => {
'5432/tcp' => [{}]
}
}, 'Env' => [ 'POSTGRES_DB=' + DB_NAME ] )
container.start
at_exit do
puts "destroying docker container: #{container.id}"
container.delete(:force => true)
end
puts "started docker container: #{container.id}"
print "waiting for database: "
retry_psql container
json = container.json
pg_port = json['NetworkSettings']['Ports']["5432/tcp"][0]["HostPort"]
ENV['DATABASE_URL'] = "postgresql://postgres@localhost:#{pg_port}/" + DB_NAME + "?pool=5"
end
end
# Other things from test.rb
config.cache_classes = true
config.eager_load = false
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=3600'
}
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_dispatch.show_exceptions = false
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :test
config.active_support.deprecation = :stderr
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment