Skip to content

Instantly share code, notes, and snippets.

@naoty
Created November 20, 2013 02:20
Show Gist options
  • Select an option

  • Save naoty/7556519 to your computer and use it in GitHub Desktop.

Select an option

Save naoty/7556519 to your computer and use it in GitHub Desktop.
ERBライブラリでテンプレート内のyieldにページを挿入するやり方
require "erb"
class Builder
def initialize(template)
@template = ERB.new(template, nil, "-")
end
def build(page)
context = Context.new(page)
@template.run(context.get_binding)
end
class Context
def initialize(page)
@page = page.rstrip
end
def get_binding
call_binding { @page }
end
private
def call_binding
binding
end
end
end
template = <<EOF
<html>
<head>
<title>builder sample</title>
</head>
<body>
<%= yield %>
</body>
</html>
EOF
page = <<EOF
<h1>page</h1>
<p>I'm in the template.</p>
EOF
Builder.new(template).build(page)
$ ruby builder.rb
<html>
<head>
<title>builder sample</title>
</head>
<body>
<h1>page</h1>
<p>I'm in the template.</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment