Render An ERB Template With A Hash Of Values

ERB is a most commonly used for rendering HTML in Rails applications, but it can also easily be used to render any text document.

require 'erb'

value = 42
ERB.new('Value: <%= value %>').result(binding) # "Value: 42"

Binding is a rather strange interface to be passing into a method call - since I was rendering templates from within a rake task I really just wanted to pass a hash of values. It turns out ERB recently introduced this functionality in Ruby 2.5, but since I’m not on the latest version I had to find a different solution.

The cleanest solution I could find was to use an OpenStruct. It’s not ideal, but it’s straightforward.

require 'erb'
require 'ostruct'

class Template < OpenStruct
  def render(erb_template)
    ERB.new(erb_template).result(binding)
  end
end

Template.new(value: 42).render('Value: <%= value %>') # "Value: 42"

Or just use Ruby 2.5!