Help us understand the problem. What is going on with this article?

database.ymlをDRYに!

More than 5 years have passed since last update.

美しくない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 入門 (初級編) アンカーとエイリアス

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした