2

i have a question about calling template expression methods from another template expression.

The example below didn't work, ie. it doesn't expand and 'prints' the code on the spot it was called. How can I modify this code to print the result of ResourceGenerator().generate(resource) on the spot where it is called? Note that ResourceGenerator().generate(resource) is in itself a template expression.

class ServerGenerator extends RESTServiceGenerator {
       def generate(Server it) '''
          package nl.sytematic.projects.RESTServiceServlet;
          import javax.ws.rs.GET;
          import javax.ws.rs.Path;
          import javax.ws.rs.Produces;
          import javax.ws.rs.core.MediaType;


          @Path("«it.baseURI»")
          public class «it.name» {
              «it.resources.forEach[ resource |new ResourceGenerator().generate(resource)]»

          }

       '''

}

Hope I am clear in my question. An example would be great! (Again: ResourceGenerator().generate returns a CharSequence).

Marten Sytema
  • 1,906
  • 3
  • 21
  • 29

1 Answers1

6

forEach always returns null and is just about doing side-effects. What you want is a map and a join.

it.resources.map(resource |new ResourceGenerator().generate(resource)).join

But there's an even better way:

«FOR resource : resources»
  «new ResourceGenerator().generate(resource)»
«ENDFOR»

I suggest to hold and reuse a single instance of ResourceGenerator as a field (do you use dependency injection?) or make ResourceGenerator::generate static.

Sven Efftinge
  • 3,065
  • 17
  • 17
  • Thanks! Yes, one of these options will be incorporated. Main goal was to at least get an xtend file for each first class entity in our input meta model, and obey the same hierarchy as in the meta model. This way we want to try to get a clean code generator. Thanks for the tip! – Marten Sytema Oct 02 '12 at 06:51