Rails DRY Up Your Database Configuration
由于database.yml十分小巧,我们很容易忘掉它是用YAML这种非常健壮的标记语言来写的。
我们可以利用YAML的"merge keys"特性简化配置和减少冗余:
YAML有一个叫"merge keys"的特性,它可以merge one Hash into another。
例如:
- development:
- adapter: mysql
- database: DRYUpYourDatabaseConfig_development
- username: root
- password: secret
- socket: /tmp/mysql.sock
- test:
- adapter: mysql
- database: DRYUpYourDatabaseConfig_test
- username: root
- password: secret
- socket: /tmp/mysql.sock
- production:
- adapter: mysql
- database: DRYUpYourDatabaseConfig_production
- username: root
- password: secret
- socket: /tmp/mysql.sock
我们可以利用YAML的"merge keys"特性简化配置和减少冗余:
- defaults: &defaults
- adapter: mysql
- username: root
- password: secret
- socket: /tmp/mysql.sock
- development:
- database: DRYUpYourDatabaseConfig_development
- <<: *defaults
- test:
- database: DRYUpYourDatabaseConfig_test
- <<: *defaults
- production:
- database: DRYUpYourDatabaseConfig_production
- <<: *defaults
莫愁前路无知己,天下无人不识君。