Created
June 1, 2013 05:40
-
-
Save cskevint/5689393 to your computer and use it in GitHub Desktop.
A HashBinding class takes a simple ruby hash and uses a class's binding to create the context for the rendering of an ERB template.
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 HashBinding | |
def initialize(hash) | |
hash.each do |key, value| | |
singleton_class.send(:define_method, key) { value } | |
end | |
end | |
def context | |
binding | |
end | |
end | |
data = { | |
weekday: Time.now.strftime('%A') | |
} | |
simple_template = "Today is <%= weekday %>." | |
renderer = ERB.new(simple_template) | |
hash_binding = HashBinding.new(data) | |
output = renderer.result(hash_binding.context) | |
puts output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment