December 2, 2006

Erubis - A faster alternative to ERB / eRubyPost by Peter Cooper

When the official Erubis homepage says that Erubis is a fast, secure, and very extensible implementation of eRuby, they're not joking! Check out these benchmarks:

Most Ruby developers are probably more familiar with ERB, so these numbers are a pretty big improvement. With the advent of mini-frameworks like Merb, Erubis could become an important part of any Ruby developer's arsenal.

To install Erubis, just use RubyGems: gem install erubis (it will ask for the 'abstract' gem to be installed, say yes to that)

Using Erubis

I use Erubis, along with why the lucky stiff's Sandbox, as an 'on demand' Ruby interpreter. Using Erubis is as easy as using ERB:

erb_code = Erubis::Eruby.new(data).src

This converts the eRuby/ERB code in the 'data' string into the relevant Ruby commands and assigns them to erb_code. Just use eval to get it working.

eval Erubis::Eruby.new(data).src

Or use the result method, along with an optional binding, to let Erubis manage the execution:

Erubis::Eruby.new(data).result(binding)

This example runs the script within the current binding. Naturally, you can use any other binding.