Sunday, 30 March 2014

Using the play Application in a play2 console

For people coming from java, one of the most useful tools in scala is the REPL. With sbt applications (and therefore play) you can launch the console and have access to the whole classpath of the application you are working on.
In play2 applications, many times you’ll find you need an instance of play.apli.Application to be able to instantiate some classes.
In your tests you can simply create a FakeApplication as documented on the playframework website. Unfortunately the console does not have access to the test context by default. (There might be a way to force that, not sure..maybe some sbt expert out there can leave a comment?)
Here follows a way to create an application in the play2 console. In my case I am using the securesocial plugin and I wanted to generate a password hash to use for testing. Here is what I’ve done
val application = new play.api.DefaultApplication(new java.io.File("."), 
  classOf[play.api.Play].getClassLoader, None, play.api.Mode.Test)

import securesocial.core.providers.utils.BCryptPasswordHasher

val hasher = new BCryptPasswordHasher
hasher.hash("hello")
res2: securesocial.core.PasswordInfo = PasswordInfo(bcrypt,
  $2a$10$lR6KZixogW95QbfwX7P4tuLvWlbqyp36Xw4PhVTqERRjyxy7OJ/lO,None)
That first line is the one you might want to copy ;)

No comments: