CNK's Blog

ERB in IRB

Someday I may expand this to a longer post on Ruby debugging, but until then I am writing it down so I don’t have to search for it on Stack Overflow again.

If you need to debug an erb snippet in irb, this function gives you a handy shortcut for combining the template and arbitrary instance variables. Copy it into your irb session:

    require 'erb'
    require 'ostruct'

    def erb(template, vars)
      ERB.new(template).result(OpenStruct.new(vars).instance_eval { binding })
    end

And then you can use it as follows:

    erb("Hey, <%= first_name %> <%= last_name %>", :first_name => "James", :last_name => "Moriarty")
     => "Hey, James Moriarty"

Kind of handy especially if you need to test out some ruby inside the <%= %> tag.