LoginSignup
11
10

More than 5 years have passed since last update.

database.ymlをDRYに!

Last updated at Posted at 2014-06-23

美しくないdatabase.yml

冗長な部分が多い…

development:
  database: db_development
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: dbuser
  password: "<%= ENV['DB_PASSWORD'] %>"
  port: 5432
test:
  database: db_development
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: dbuser
  password: "<%= ENV['DB_PASSWORD'] %>"
  port: 5432
staging:
  database: db_development
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: dbuser
  password: "<%= ENV['DB_PASSWORD'] %>"
  port: 5432
production:
  database: db_production
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: dbuser
  password: "<%= ENV['DB_PASSWORD'] %>"
  port: 5432

DRY!

YAMLには、アンカーとエイリアスがあったので書き直してみる

common: &common
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: dbuser
  password: <%= ENV['DB_PASSWORD'] %>
  port: 5432

development: &development
  database: db_development
  <<: *common

test: *development

staging: *development

production:
  database: db_production
  <<: *common

確認方法

% ruby -r yaml -e 'print YAML.load(ARGF.read()).delete_if {|key| key == "common"}.to_yaml' ./database.yml

こんな感じで、大体あってることが確認できる

---
development: &1
  database: db_development
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: dbuser
  password: "<%= ENV['DB_PASSWORD'] %>"
  port: 5432
test: *1
staging: *1
production:
  database: db_production
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: dbuser
  password: "<%= ENV['DB_PASSWORD'] %>"
  port: 5432

参考サイト

プログラマーのための YAML 入門 (初級編) アンカーとエイリアス

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10