YAML::Storeはブロック内で実際美しいYAMLファイルを生成できるライブラリです。
準備
require "yaml/store" store = YAML::Store.new 'list.yaml' #=> #<Psych::Store:0x007ff962926888 @abort=false, @filename="list.yaml", @lock=#<Mutex:0x007ff962926770>, @opt={}, @thread_safe={}, @ultra_safe=false>
データ投入
ブロックの中で記述。ブロック変数不要。実際便利
store.transaction do store[:first] = 123 store[:second] = 456 end p store #<Psych::Store:0x007ff962926888 @opt={}, @filename="list.yaml", @abort=false, @ultra_safe=false, @thread_safe={}, @lock=#<Mutex:0x007ff962926770>, @rdonly=false, @table={:first=>123, :second=>456}> #=> #<Psych::Store:0x007ff962926888 @abort=false, @filename="list.yaml", @lock=#<Mutex:0x007ff962926770>, @opt={}, @rdonly=false, @table={:first=>123, :second=>456}, @thread_safe={}, @ultra_safe=false>
*中断
ブロック中で中断も大丈夫。
store.transaction do store[:first] = 42 store.abort store[:second] = 42 end => nil p store #<Psych::Store:0x007ff962926888 @opt={}, @filename="list.yaml", @abort=true, @ultra_safe=false, @thread_safe={}, @lock=#<Mutex:0x007ff962926770>, @rdonly=false, @table={:first=>42, :second=>456}> => #<Psych::Store:0x007ff962926888 @abort=true, @filename="list.yaml", @lock=#<Mutex:0x007ff962926770>, @opt={}, @rdonly=false, @table={:first=>42, :second=>456}, @thread_safe={}, @ultra_safe=false>
全てが終わった後でlist.yamlを確認すると...
$ cat list.yaml --- :first: 123 :second: 456
ワザマエ! 見事立派なYAMLファイルになった!