Wednesday, May 20, 2009

Using Ruby and ERB for code generation

In my current project (using Java, Spring MVC and ExtJS), we have a lot of modules for data entry and since there were similarities in all the modules (and the fact is we had like 20 of these to code) we decided to take a closer look at code generation.

But what tool to use? Stumble upon ruby in the book Code Generation in Action and found a chapter on code templates and the example uses Ruby and ERBs. I thought wasn't ERB's used in Rails like JSP's? I thought i needed to write web programs in order to generate the code. But boy was i wrong, we could actually use ERBs from any Ruby programs.

Sample of the ruby file - test.rb

[sourcecode language='ruby']
require 'erb'

erb=ERB.new(File.open("test.erb").read());
name='Stephen';
code=erb.result(binding);
print code;
[/sourcecode]

Sample of the ERB file - test.erb

[sourcecode language='ruby']
public class <%=name%>{
}
[/sourcecode]

What's happening here, the name variable that you defined in test.rb is passed to the erb file when erb.result(binding) is execute and it returns the results of the erb file. You can pass in arrays, hashes from the code to the erb file easily just by calling the erb.result(binding) method.

Our experience - Great ! We wrote generators to generate our javascript menus, spring MVC views (which are in ExtJS) to Spring Controller to Hibernate DAOs. It does save us sometime in do repertitive work.

If your project has lots of similar components that you need to code. Why not take a look at code templating using Ruby and ERB.

No comments:

Post a Comment