Created
November 20, 2013 02:20
-
-
Save naoty/7556519 to your computer and use it in GitHub Desktop.
ERBライブラリでテンプレート内のyieldにページを挿入するやり方
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $ 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