Ruby File Generation
Join me on a journey through using ruby to generate java, learning how to use the built in ruby templating tool erb, and some of the rubyish techniques that erb leverages.
Our adventure starts with a need to generate a large number of very simple java classes in order to have a nice simple test case for the boys at sun. The requirements for the classes are:
- they are some how different
- it is easy to tell when each class is loaded by the class loader
- it is easy to tell when each class is instantiated
These requirements would be painful to meet (when creating 1000+ classes) even in the most powerful java IDE. An automated technique for generating code. In steps Ruby and erb.
A basic ruby script which has a simple template to base the files on, and creates the java classes.
require 'erb' #we are using the erb library.
# create an erb template using the multiline string starting after EOF,
# and finishing at the EOF below.
template=ERB.new <<EOF
packageephox;
public class SimpleClass<%=class_number%> {
static {
System.out.println("static SimpleClass<%=class_number%>");
}
public SimpleClass<%=class_number%>() {
super();
System.out.println("init SimpleClass<%=class_number%>");
}
}
EOF
5.times do |counter| # perform code in this loop five times, remembering the counter.
class_number=counter+1
File.open "src/ephox/SimpleClass#{class_number}.java" ,'w' do |file|
# open the file for writing.
file.puts template.result(binding)
#merge the template into the file, passing in the current binding.
end
end
In looking back over the example, you can see some interesting rubyisms. These are some of the spots where ruby is revealed. Note the following:
- the use of closures (File.open, and 5.times),
- everything really is an object (the method times being called on the object literal 5),
- heredoc notation (<<EOF )
- the ease of templating with erb (which keeps normal ruby syntax in the template),
The statement I made above about everything being an object is pushed to its limits when looking at the method call: template.result(binding). The binding method is available as a part of the Kernel, a mixin(providing methods for use) that is a part of Object, the mighty superclass of everything in Ruby. This method will return a Binding object, which erb uses to get data to merge into the template.
The File.open line opens a file in write mode, overriding the contents of the file. For more examples of how to do this, look at the PLEAC site, which has a good set of ruby file examples, and quite a complete set of ruby examples. This is an excellent resource for learning a language.
In all, Ruby does a good job of working with files, and templating. Erb is a great tool for templating, and forms the backbone of many well known ruby programs.