tags:

views:

1051

answers:

3

What's the difference between eruby and erb? What considerations would drive me to choose one or the other?

My application is generating config files for network devices (routers, load balancers, firewalls, etc.). My plan is to template the config files, using embedded ruby (via either eruby or erb) within the source files to do things like iteratively generate all the interface config blocks for a router (these blocks are all very similar, differing only in a label and an IP address). For example, I might have a config template file like this:

hostname sample-router
<%=
r = String.new;
[
    ["GigabitEthernet1/1", "10.5.16.1"],
    ["GigabitEthernet1/2", "10.5.17.1"],
    ["GigabitEthernet1/3", "10.5.18.1"]
].each { |tuple|
    r << "interface #{tuple[0]}\n"
    r << "    ip address #{tuple[1]} netmask 255.255.255.0\n"
}
r.chomp
%>
logging 10.5.16.26

which, when run through an embedded ruby interpreter (either erb or eruby), produces the following output:

hostname sample-router
interface GigabitEthernet1/1
    ip address 10.5.16.1 netmask 255.255.255.0
interface GigabitEthernet1/2
    ip address 10.5.17.1 netmask 255.255.255.0
interface GigabitEthernet1/3
    ip address 10.5.18.1 netmask 255.255.255.0
logging 10.5.16.26
+5  A: 

Doesn't really matter, they're both the same. erb is pure ruby, eruby is written in C so it's a bit faster.

erubis (a third one) is pure ruby, and faster than both the ones listed above. But I doubt the speed of that is the bottleneck for you, so just use erb. It's part of Ruby Core.

Jordi Bunster
+1  A: 

Eruby is an external executable, while erb is a library within Ruby. You would use the former if you wanted independent processing of your template files (e.g. quick-and-dirty PHP replacement), and the latter if you needed to process them within the context of some other Ruby script. It is more common to use ERB simply because it is more flexible, but I'll admit that I have been guilty of dabbling in eruby to execute .rhtml files for quick little utility websites.

Daniel Spiewak
A: 

I'm doing something similar using erb, and the performance is fine for me.

As Jordi said though, it depends what context you want to run this in - if you're literally going to use templates like the one you listed, eruby would probably work better, but I'd guess you're actually going to be passing variables to the template, in which case you want erb.

Just for reference, when using erb you'll need to pass it the binding for the object you want to take variables from, something like this:

device = Device.new
device.add_interface("GigabitEthernet1/1", "10.5.16.1")
device.add_interface("GigabitEthernet1/2", "10.5.17.1")

template = File.read("/path/to/your/template.erb")
config = ERB.new(template).result(device.binding)
Jon Wood