Postgres

Set up postgresql as the database
Icons/chart bar
Used 39 times
Created by
L Luna Comerford

Usage

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/XvEskg"
Template Source

Review the code before running this template on your machine.

`which postgres`
isPostgresInstalled =  $?
if not isPostgresInstalled.success? 
  puts "Postgres doesn't appear to be installed. Please install before continuing!"
  exit
end

`pg_ctl -D /usr/local/var/postgres status`
isPostgresRunning =  $?
if not isPostgresRunning.success? 
  puts "Postgres doesn't appear to be running. Attempting to start..."
  system("pg_ctl -D /usr/local/var/postgres start")
  didPostgresStart =  $?
  
  puts "Unable to start postgres server!" unless didPostgresStart.success?
  exit unless didPostgresStart.success?
end

puts "Creating #{app_name} user role..."
system("createuser -s #{app_name}")
if not $?.success?
  puts "Error creating #{app_name} user role!"
  exit
end

gem 'pg'
gsub_file 'Gemfile', /gem 'sqlite3'.*/, ''

Bundler.with_unbundled_env { run 'bundle install' }

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:
    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

system('rake db:drop')
system('rake db:create')
system('rake db:migrate')
Comments

Sign up or Login to leave a comment.