Calling into Play framework app from the Scala console
Asked Answered
P

2

10

I have a Play Framework 2.3 app. I can drop into a Scala console with activator console. However, when I try to call into code from my app, specifically some helper function which uses WS, which uses the implicit import play.api.Play.current to retrieve the currently running app, I get the error message java.lang.RuntimeException: There is no started application.

What steps do I have to take to be able to load my app into the current console session?

There is a similar existing question, but the accepted answer appears to be using a mock app from the framework's test helpers. Preferably, I would like to run in the context of my actual app. If I must use a fake app, would it be possible to make it match my development environment (what I get when running activator run) rather than my test environment (what I get when running the unit tests)?

Thanks in advance!

Pegram answered 25/3, 2015 at 7:28 Comment(4)
What's the goal of running in such way?Tourneur
@Tourneur It's nice to be able to play with things in the REPL.Torsk
Similarly, you can use StaticApplication #24435915 This question essentially asks the same thing, except for models that require the database. The common ground is that they both require the implicit app.Torsk
This answer might help: #31224687Phocis
E
8

In this specific case you can just create an Application instance and use it instead of the implicit one:

// Tested in 2.3.7
import play.api.{Play, Mode, DefaultApplication}
import java.io.File
import play.api.libs.ws.WS

val application = new DefaultApplication(
    new File("."),
    Thread.currentThread().getContextClassLoader(),
    None,
    Mode.Dev
)

import scala.concurrent.ExecutionContext.Implicits.global

WS.client(application).url("http://www.google.com").get().map((x) => println(x.body))
Embarkation answered 25/3, 2015 at 12:33 Comment(1)
Tks for this. I needed an additional Play.start(application) to get goingConvexity
T
8

For future readers, for Play framework 2.5.x:

import play.api._
val env = Environment(new java.io.File("."), this.getClass.getClassLoader, Mode.Dev)
val context = ApplicationLoader.createContext(env)
val loader = ApplicationLoader(context)
val app = loader.load(context)
Play.start(app)

Source: https://www.playframework.com/documentation/2.5.x/PlayConsole#Launch-the-interactive-console

Trap answered 17/11, 2016 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.