I don’t know if this matches the “more elegant” or not:
require 'erb' require 'ostruct' class ErbalT < OpenStruct def render(template) ERB.new(template).result(binding) end end et = ErbalT.new({ :first => 'Mislav', 'last' => 'Marohnic' }) puts et.render('Name: <%= first %> <%= last %>')
Or from a class method:
class ErbalT < OpenStruct def self.render_from_hash(t, h) ErbalT.new(h).render(t) end def render(template) ERB.new(template).result(binding) end end template = 'Name: <%= first %> <%= last %>' vars = { :first => 'Mislav', 'last' => 'Marohnic' } puts ErbalT::render_from_hash(template, vars)
(ErbalT has Erb, T for the pattern and sounds like “herbal tea.” Naming things is complicated.)
Dave Newton Jan 21 '12 at 17:40 2012-01-21 17:40
source share