Skip to content

Instantly share code, notes, and snippets.

@cskevint
Created June 1, 2013 05:40
Show Gist options
  • Save cskevint/5689393 to your computer and use it in GitHub Desktop.
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.
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