0
votes

I have a Play! framework with two actions which contain redundant code. So I factored this code into a private static method, but It doesn't work anymore then.

  public static void show(long itemId, String listId) {
    render(getItem(itemId, listId));
  }

  private static Item getItem(long itemId, String listId) {
    // otherwise duplicate code ...
    return item;
  }

If I inline the code contained in getItem into the show action everything is fine:

  // this works
  public static void show(long itemId, String listId) {
    Item item = // duplicate code ...
    render(item);
  }

Why can I not call other static methods within a Play! controller?

Solution

Thanks to 'Codemwnci' I've implemented the following solution:

  public static void show(long itemId, String listId) {
    renderArgs.put("item", getItem(itemId, listId));
    render();
  }

I prefer renderArgs because it makes the intention more clear than a local variable.

1
Have in mind that if you make the helper-method public a redirect is happened. See stackoverflow.com/questions/3899670/…. This isn't your problem now, but could be the next, where some magic happens. - niels
Thanks, I'm aware of it. - deamon

1 Answers

4
votes

When you pass a local variable into the render method, the name of the local variable is used when passed through to the Groovy view. In your example, you are not passing a local variable, therefore Play does not know what name to give the item you have specified.

You have a couple of options. You can do either

  1. Set the return from getItem to a local variable (item), and pass item into the view
  2. Set the return from getItem into the renderArgs map, and specify your own name.

Option 1 is probably the most sensible.