0

I want to add methods to my datamodel so I need a way to specify them inside my tdd data file(s). For example having a tdd data file containing two scalars :

a: 1
b: 1 

I would like to add a method area which multiplies them. Is this even possible and if so how do I achieve this?

user10568173
  • 61
  • 1
  • 7

1 Answers1

1

So let's say you have MyUtils that has a foo() and a bar() methods, and you want to access those in the templates.

You can add an arbitrary Java objects to the model using the eval data loader in data, like myUtils: eval('new com.example.MyUtils()'). Then you can issue myUtils.foo() in the templates. But, you wanted to add the methods at top level. That's also possible. Both in eval and in a custom DataLoader (whichever you want to use) you have access to engine, the fmpp.Engine object. And then you can pull this trick:

// Note: In case you are using eval, use Java 1.2 syntax (no generics).
TemplateHashModel myUtilsModel = (TemplateHashModel) engine.wrap(new MyUtils());
Map<String, TemplateModel> myUtilsMethodModels = new HashMap<>();
myUtilsMethodModels.put("foo", myUtilsModel.get("foo"));
myUtilsMethodModels.put("bar", myUtilsModel.get("bar"));
return myUtilsMethodModels;

Then you add that Map to data without a name. (If you add a Map to data without a name, its keys become top-level variables.)

Certainly it can be polished to be nicer, like find methods you want automatically, etc. Plus I did not try this above (so typos are possible). But this is the basic idea. (I guess it would be practical if FMPP had a data loader that loads the static methods of a class... But, right now it doesn't have that.)

ddekany
  • 29,656
  • 4
  • 57
  • 64