Postgres with docker-compose
Set up postgresql as the database with local support for docker-compose
Used 184 times
T
TobiasBales
Usage
Run this command in your Rails app directory in the terminal:
rails app:template LOCATION="https://railsbytes.com/script/xGqs7b"
Template Source
Review the code before running this template on your machine.
gem 'pg'
gsub_file 'Gemfile', /gem 'sqlite3'.*/, ''
Bundler.with_unbundled_env { run 'bundle install' }
unless File.exist? 'docker-compose.yml'
create_file 'docker-compose.yml' do <<~YAML
version: "3.1"
services:
YAML
end
end
inject_into_file 'docker-compose.yml' do <<-YAML
db:
image: postgres
restart: always
environment:
POSTGRES_USER: #{app_name}
POSTGRES_PASSWORD: #{app_name}
POSTGRES_DB: #{app_name}_development
volumes:
- ./tmp/postgresql:/var/lib/postgresql
ports:
- 5432:5432
YAML
end
initializer 'generator.rb' do <<~RB
Rails.application.config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
RB
end
remove_file 'config/database.yml'
create_file 'config/database.yml' do <<~EOF
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: #{app_name}_development
username: #{app_name}
password: #{app_name}
host: localhost
port: 5432
test:
<<: *default
database: #{app_name}_test
username: #{app_name}
password: #{app_name}
host: localhost
port: 5432
production:
<<: *default
url: <%= ENV['DATABASE_URL'] %>
EOF
end
generate 'migration', 'enable_uuid'
migration = Dir.glob("db/migrate/*").max_by { |f| File.mtime(f) }
inject_into_file migration, after: 'def change' do <<~RB
enable_extension 'pgcrypto'
RB
end
`docker-compose up --detach`
sleep 2
system('rake db:drop')
system('rake db:create')
system('rake db:migrate')