YAMLのノードには3種類(kind)がある:
- Scalar (Unicodeの文字列として表現できるもの)
- Sequence (配列みたいなもの)
- Mapping (連想配列やHashみたいなもの)
それぞれのkindはいくつかのstyleで出力できる。
- Scalar:
- Plain (1行)
1 Lorem ipsum dolor sit amet, consectetur adipiscing elit.
- Single Quote (1行)
1 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
- Double Quote (1行)
1 "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
- Block Literal (改行がそのまま残る)
1 --- |
2 Lorem ipsum dolor sit amet,
3 consectetur adipiscing elit.
4 Pellentesque tincidunt molestie est.
5 Vestibulum ante odio, euismod ac,
6 sagittis et, tempus ut, lorem.
7 Praesent consectetur tempor ipsum.
8 Nulla facilisi.
- Block Folding (改行が空白になる)
1 --- >
2 Lorem ipsum dolor sit amet,
3 consectetur adipiscing elit.
4 Pellentesque tincidunt molestie est.
5 Vestibulum ante odio, euismod ac,
6 sagittis et, tempus ut, lorem.
7 Praesent consectetur tempor ipsum.
8 Nulla facilisi.
- Sequence
- デフォルト
1 - one
2 - two
3 - three
- inline
1 [1, 2, 3]
- Mapping
- デフォルト
1 height: 170
2 weight: 60
- inline
1 { height: 170, weight: 60}
YAML::dumpでオブジェクトをダンプしたい時、styleを統一する場合もある。が、YAML::dumpにはstyleを指定する機能はない。そこで、to_yaml_style
をオブジェクトに定義すればよい、という裏技(非ドキュメントメソッド)を紹介したい。このメソッドの返り値がそのオブジェクトのstyleになる。
例えば:
1 class String
2 def to_yaml_style
3 return :quote2
4 end
5 end
をすれば、YAML::dump
のすべての文字列がダブルクオートに囲まれる。
Rubyでのスタイルは以下:
1 :plain
2 :quote1
3 :quote2
4 :literal
5 :fold
6 :inline
7 nil
ちなみに、これを調べた切っ掛けはHashをYAML::dumpした時にvalueの方にクオートがあったりなかったりしたからです。つまりこれ:
1 name: "鈴木"
2 height: 170
3 weight: 60
をこれにする:
1 name: "鈴木"
2 height: "170"
3 weight: "60"
monkeypatch的な解決方法:
1 class Hash
2 def to_yaml_with_quoted_strings(*args)
3 class << self
4 unless method_defined?(:each_with_quoted_strings)
5 def each_with_quoted_strings
6 each_with_normal_strings do |k,v|
7 if String === v && !v.frozen?
8 def v.to_yaml_style; return :quote2; end
9 end
10 yield k, v
11 end
12 end
13 alias_method :each_with_normal_strings, :each
14 alias_method :each, :each_with_quoted_strings
15 end
16 end
17 return to_yaml_with_normal_strings(*args)
18 end
19 alias_method :to_yaml_with_normal_strings, :to_yaml
20 alias_method :to_yaml, :to_yaml_with_quoted_strings
21 end
gist