Thursday, October 27, 2005

Hibernate & Ruby


In my previous project I was using the latest and greatest version of Hibernate and was happily employing the Hibernate Eclipse plugin for writing my HQL queries before embedding them in my application. But my current project uses an older version of Hibernate (2.1.x) so the Eclipse plugin is out of the question. Fortunately I can remember back to when I used the forerunner of the Eclipse plugin, a little program that was called Hibern8IDE. It later became part of the Hibernate extension tools and was then thankfully renamed "Hibernate Console". Fortunately it's still available for download from hibernate.org.

Now the only problem is that this project also uses Spring which informs Hibernate about the XDoclet-generated mapping files at runtime in a decidedly non-hibernate fashion. What I needed was to create a good old fashioned hibernate.cfg.xml which contains references to each *.hbm.xml file. But I wanted to script the generation of this file so that I wouldn't have to manually maintain the file as the collection of *.hbm.xml changes over time. So I turned to my new friend Ruby. The top and bottom part of this script use "here docs" to generate the boiler plate static XML. But then right in the middle I got this:


`find . -name '*.hbm.xml' -print`.each { |f|
f.gsub!(/.*(com\/company.*?)\n/, '\1')
puts "<mapping resource=\"#{f}\"/>"
}


The first line executes the Unix find command, and then begins an iterator over each line of that command's results. Then within the block I use a simple regex within the String's substitution method to get the Java package and file name. Then finally I print out an XML element whose resource attribute contains the name of the *.hbm.xml file. That's a lot of stuff in only four lines of code! Ruby is very expressive. Now I must emphasize the value of a good editor to color code something like that so a person can make sense of it. I definitely recommend the RDT plugin for Eclipse.

No comments: