A hash is a great way to manage a list of key/value pairs, and templates are a great way to render content. So here’s a simple way to render a template from a hash.
template.erb
My favorite color is <%= favorite_color %>.
render.rb
require 'erb'
require 'ostruct'
opts = OpenStruct.new({
:favorite_color => ARGV[0]
})
template = open('template.erb', 'r') {|f| f.read}
puts ERB.new(template).result(opts.instance_eval {binding})
require 'ostruct'
opts = OpenStruct.new({
:favorite_color => ARGV[0]
})
template = open('template.erb', 'r') {|f| f.read}
puts ERB.new(template).result(opts.instance_eval {binding})
So running
ruby render.rb blue
will output this
My favorite color is blue.
Which is cool. The interesting parts (and the reason I’m writing this) are that you need to instantiate a new OpenStruct from your hash so that its members can be accessed as methods, and then you have to set the binding for ERB by saying opts.instance_eval {binding}. This runs binding in the context of the opts object, so then calls to methods like favorite_color made by ERB in this context will evaluate to the values of our hash.