Working on a JRuby script that accesses a Java Content Repository I was missing a method on javax.jcr.Node that would return the whole subtree of child nodes. Ruby and the JRuby implementation allow to re-open classes and add new code. In that way one can easily extend even core classes (or interfaces as in this case):
JavaUtilities.extend_proxy("javax.jcr.Node") do
def getAllNodes
all = Array.new
children = self.getNodes
children.each {|child| all.push(child);
all.push(child.getAllNodes)}
all.flatten
end
end
This extends regular JCR nodes with a method getAllNodes that returns a flat array of all child nodes. Speaking of fixing issues one might have with existing objects: recently, I was unhappy with the fact that repository.getDescriptor( Repository.OPTION_OBSERVATION_SUPPORTED) returns a String instead of a Boolean because it makes me write code like:
if (repository.getDescriptor(
Repository.OPTION_OBSERVATION_SUPPORTED)
.equals("true"))
The fix is obviously:
JavaUtilities.extend_proxy("javax.jcr.Repository") do
def getRealDescriptor(name)
if self.getDescriptor(name) == "true" ||
self.getDescriptor(name) == "false"
self.getDescriptor(name) == "true"
else
self.getDescriptor(name)
end
end
end
(Actually I wanted to use alias_method to redefine getDescriptor instead of defining a new method, but could not figure out how to do this on an interface. If you know it, please leave a comment.)
