分享 Yaml 代码复用技巧

ery · June 03, 2012 · Last by googya replied at June 04, 2012 · 6541 hits

背景

昨天因为想复用国际化 i18n yml 中的一部分代码 于是 google 了一下 yaml 语法 发现 yaml 语法天生有'复用机制' 于是和大家分享一下

代码 1 等效于 代码 2

代码 1

bill: &bill_share
  number:  编号
  total:   总额
  deal_at: 交易日期

sale: *bill_share
purchase: *bill_share

代码 2

sale:
  number:  编号
  total:   总额
  deal_at: 交易日期

purchase:
  number:  编号
  total:   总额
  deal_at: 交易日期

重点资料 Advanced components of YAML

http://en.wikipedia.org/wiki/YAML

# sequencer protocols for Laser eye surgery
---
- step:  &id001                  # defines anchor label &id001
    instrument:      Lasik 2000
    pulseEnergy:     5.4
    pulseDuration:   12
    repetition:      1000
    spotSize:        1mm

- step: &id002
    instrument:      Lasik 2000
    pulseEnergy:     5.0
    pulseDuration:   10
    repetition:      500
    spotSize:        2mm

- step: *id001                   # refers to the first step (with anchor &id001)
- step: *id002                   # refers to the second step
- step: *id001
- step: *id002

有关资料

http://en.wikipedia.org/wiki/YAML http://www.yaml.org/refcard.html http://www.yaml.org/spec/1.2/spec.html

database.yml 的写法

default: &default
  adapter: mysql2
  encoding: utf8
  reconnect: false
  pool: 5
  username: root
  password: root
  host: localhost

development:
  <<: *default
  database: exam_development

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: exam_test

production:
  <<: *default
  database: exam_production

我记得 rails 刚出来的时候就拿这个当 DRY 的例子。

#2 楼 @hooopo ^_^,我没印象

这。。。。。平常数据库中 yml 文件不就是这样做的么?

You need to Sign in before reply, if you don't have an account, please Sign up first.