Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use postgres in a Rails app template?

I'm creating a custom template for an app, and I added pg to be used instead of sqlite:

gem 'pg'

gsub_file "Gemfile", /^gem\s+["']sqlite3["'].*$/,''

after_bundle do
  generate "rspec:install"
  generate "simple_form:install"
end

However, if I create the application like this, the database.yml file if going to be configured for sqlite3 by default, how can I specify the app to add the configuration for postgresql instead from my template? just as I were adding the --database=postgresql option

like image 637
Carlos Martinez Avatar asked Oct 18 '22 15:10

Carlos Martinez


1 Answers

It isn't needed to ask the user for the application name, as app_name is already populated with it.

Thor commands are incredibly helpful for working with files, it is possible to use .erb templates and pass them values from your template, using the template method:

# config the app to use postgres
remove_file 'config/database.yml'
template 'database.erb', 'config/database.yml'

database.erb:

default: &default
  adapter: postgresql
  host: db 
  port: 5432
  pool: 5
  timeout: 5000
  user: postgres
  password: postgres

development:
  <<: *default
  database: <%= app_name %>_development

test:
  <<: *default
  database: <%= app_name %>_test

production:
  <<: *default
  database: <%= app_name %>_production
like image 81
Carlos Martinez Avatar answered Oct 31 '22 20:10

Carlos Martinez