How do I enable "know" that they are being executed in the context of a response in groovy?

I am calling some cloud that allows groovy scripts to execute. I am returning data as xml from these scripts. I am using the code like this:

def writer;
def xml;
writer = new StringWriter();
xml = new MarkupBuilder(writer);

xml.Response() {
   node('arrtibute1': value4arrtibute1);
}

      

But I need to use a more complex way of calculating values. I want to place many different nodes in it.

def writer;
def xml;
writer = new StringWriter();
xml = new MarkupBuilder(writer);

xml.Response() {
   Function1();
   Function2();
}

      

... and the implementation of these functions.

public void Function1(){
   node1('arrtibute1': value4arrtibute1);
}
public void Function2(){
   someOtherNode1('arrtibute1': otherValue4arrtibute1, ...);
}

      

The last code doesn't work. The reason it doesn't work is for functions that don't know they are working in the context of the response and are looking for methods node1

and someOtherNode1

.

When I try to pass xml in functions and try to create a new answer, there I have distorted the structure of the XML document (document in document).

My question is, how do I get the code in the function to "know" that they run in the context of the response?

+3


source to share


2 answers


You need to pass to the builder the functions you call like this:



import groovy.xml.MarkupBuilder

value4arrtibute1 = 'val1'
otherValue4arrtibute1 = 'val2'

public void function1( MarkupBuilder builder ){
   builder.node1('arrtibute1': value4arrtibute1 )
}

public void function2( MarkupBuilder builder ){
   builder.someOtherNode1('arrtibute1': otherValue4arrtibute1 )
}

String output = new StringWriter().with { writer ->
  new MarkupBuilder(writer).with { xml ->
    xml.Response() {
      function1( xml )
      function2( xml )
    }
  }
  writer
}

println output

      

+3


source


@tim_yates is correct in his answer, although I would like to share another method of doing the same action without having to pass a builder or delegate.

In practice, I would normally make the functions function1 and function2 Closures and assign them to the builder delegates.



import groovy.xml.MarkupBuilder

value4arrtibute1 = 'val1'
otherValue4arrtibute1 = 'val2'

Closure function1 = {
   node1('arrtibute1': value4arrtibute1 )
}

Closure function2 = {
   someOtherNode1('arrtibute1': otherValue4arrtibute1 )
}

String output = new StringWriter().with { writer ->
  new MarkupBuilder(writer).with { xml ->
    xml.Response() {
      firstNode()
      xml.with function1
      xml.with function2
    }
  }
  writer
}

println output

      

+1


source







All Articles