erbのyield
railsのviewの処理のように、erbのソースにyieldを使ってhtmlを埋めこむようなテクニックがあるけど、nanocのソースを読んでいたら、同様の処理を行うようなコードがあった。erbとyieldの使い方をメモしておこう。
erbのyieldは以下のように使える。
>> require 'erb' => true >> class Context >> def get_binding >> binding >> end >> end => nil >> layout =<<EOS <html> <body> <%= yield %> </body> </html> EOS => "<html>\n<body>\n <%= yield %>\n</body>\n</html>\n" >> content = "content" => "content" >> e = ERB.new(layout) => #<ERB:0x18f9b75 @filename=nil, @src="_erbout = ''; _erbout.concat \"<html>\\n<body>\\n \"\n\n; _erbout.concat(( yield ).to_s); _erbout.concat \"\\n</body>\\n</html>\\n\"\n\n\n; _erbout", @safe_level=nil> >> e.result(Context.new.get_binding{ content }) => "<html>\n<body>\n content\n</body>\n</html>\n"
ERB#resultにブロックを付けたbindingを渡せばよい。
ブロックが無いと、以下のように例外が出る。
>> e.result LocalJumpError: yield called out of block from /opt/env/ruby/jruby-1.5.0/lib/ruby/1.8/irb/ruby-token.rb:46 Maybe IRB bug!! >> e.result(binding) LocalJumpError: yield called out of block from /opt/env/ruby/jruby-1.5.0/lib/ruby/1.8/irb/ruby-token.rb:102:in `irb_binding' Maybe IRB bug!! >> e.result(Context.new.get_binding) LocalJumpError: yield called out of block from /opt/env/ruby/jruby-1.5.0/lib/ruby/1.8/irb/ruby-token.rb:102:in `get_binding' Maybe IRB bug!!