<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users551</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/551" rel="self"/>
  <title>Sam Stephenson</title>
  <updated>Sat Apr 12 17:34:10 -0700 2008</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor4878</id>
    <published>2008-04-12T17:34:10-07:00</published>
    <title>[Ruby] On Given a hash of variables, render an ERB template</title>
    <content type="html">

&lt;pre&gt;require &amp;quot;erb&amp;quot;

class Hash
  def to_binding(object = Object.new)
    object.instance_eval(&amp;quot;def binding_for(#{keys.join(&amp;quot;,&amp;quot;)}) binding end&amp;quot;)
    object.binding_for(*values)
  end
end

class Document
  def initialize(template)
    @template = ERB.new(template)
  end
  
  def interpolate(replacements = {})
    @template.result(replacements.to_binding)
  end
end

puts Document.new(&amp;quot;Name: &amp;lt;%= first %&amp;gt; &amp;lt;%= last %&amp;gt;&amp;quot;).interpolate(:first =&amp;gt; &amp;quot;Mislav&amp;quot;, &amp;quot;last&amp;quot; =&amp;gt; &amp;quot;Marohnic&amp;quot;)
# Name: Mislav Marohnic

&lt;/pre&gt;</content>
    <author>
      <name>Sam Stephenson</name>
      <email>sstephenson@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/281-given-a-hash-of-variables-render-an-erb-template/refactors/4878" rel="alternate"/>
  </entry>
</feed>

