views:

50

answers:

1

I'm trying to create a DSL that can easily use a dom node. Using DOMCategory is nice, but adds the noise of 'use(DOMCategory)'. Is there a way to avoid that?

I tried wrapping the script call inside a call to 'use', but this doesn't seem to work in closures.

+1  A: 

You can use groovy's runtime mixin feature to permanently mix in the category. Class.mixin adds the applicable methods in the category to the class's metaClass. Apply it to the classes and interfaces that appear as the first parameter to each category method, and the category will be available without enclosing the code in a use(DOMCategory) block.

Example:

import org.w3c.dom.*
import groovy.xml.DOMBuilder
import groovy.xml.dom.DOMCategory

[Node, NodeList, NamedNodeMap, DOMCategory.NodesHolder]*.mixin DOMCategory

def sampleXml = '''
  <sample>
    <someNode anAttribute='foo'>bar</someNode>
  </sample>
'''

def sample = DOMBuilder.parse(new StringReader(sampleXml)).documentElement

println sample.someNode*.tagName
println sample.someNode[0].'@anAttribute'
println sample.someNode[0].attributes['anAttribute']

Gives:

[someNode]
foo
foo
ataylor