Michiel Borkent
Michiel Borkent

Reputation: 34840

Reduce boilerplate in Play 2 controller methods

I have a Play Controller that has a couple of methods that are very similar. I wondered how I can reduce boilerplate:

public static Result foo() {
  // boilerplate
  if (!PREVIEW) {
    return redirect(routes.Application.login());
  }
  // other code
  ...
  return ok("...");
}

public static Result bar() {
  // boilerplate
  if (!PREVIEW) {
    return redirect(routes.Application.login());
  }
  // other code
  ...
  return ok("...");
}

PREVIEW is shorthand for a configuration setting.

Upvotes: 1

Views: 50

Answers (1)

Michiel Borkent
Michiel Borkent

Reputation: 34840

I created an Action like this:

public class PreviewAction extends Action.Simple {
    public F.Promise<Result> call(Http.Context ctx) throws Throwable {
        if (!PREVIEW) {
            return F.Promise.pure(redirect(routes.Application.login()));
        }
        return delegate.call(ctx);
    }
}

Now I can use an annotation on my other actions and it works like it did before:

@With(PreviewAction.class)
public static Result foo() {
  ...
}

More information: https://www.playframework.com/documentation/2.4.x/JavaAsync

Thanks to Tunaki for pointing me in the right direction.

Upvotes: 1

Related Questions