YAML+ERB

前回の続きで、ERB に埋め込む情報を YAML で記述する実験。

# config.yml
books:
-
title: あいうえお
author: かきくけこ
price: 400
-
title: さしすせそ
author: たちつてと
price: 800
#!/usr/bin/ruby -Ku
require 'erb'
require 'yaml'
erb_doc = <<EOS
hello world 1
<% config['books'].each_with_index do |i,n| -%>
[<%= n %>] title:<%= i['title'] %> / author:<%= i['author'] %>
<% end -%>
hello world 2
EOS
class MyTemplate
def initialize
@config = YAML.load(File.new('config.yml'))
end
def config
@config
end
def result(script)
ERB.new(script, nil, '-').result(binding)
end
end
puts MyTemplate.new.result(erb_doc)
# hello world 1
# [0] title:あいうえお / author:かきくけこ
# [1] title:さしすせそ / author:たちつてと
# hello world 2

投稿日

カテゴリー:

投稿者:

タグ: