Skip to content

Instantly share code, notes, and snippets.

@eboto
Created November 9, 2012 10:18
Show Gist options
  • Save eboto/4045003 to your computer and use it in GitHub Desktop.
Save eboto/4045003 to your computer and use it in GitHub Desktop.
Example of how types could work together in toybox
package controllers
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
/** Imagine that the stuff inside this package is the toybox plugin code */
package toybox {
/**
* ToyBox. This is the only type the client app has to care about. To use it:
*
* 1. Mix it in with an object in the real application (e.g. object MyToyBox extends ToyBox)
* 2. Route the ToyBox controllers to whatever routes you want in your routes file, e.g.
* GET /login MyToyBox.Controllers.getLogin
* POST /login MyToyBox.Controllers.postLogin
* 3. Implement the abstract members getLogin and postLogin using the reverse router, e.g.
* 4. Enable the plugin located at MyToyBox.Plugin
*/
trait ToyBox extends TBRoutes with TBPlugin with TBControllers
trait TBRoutes {
def getLogin: Call
def postLogin: Call
}
/** This provides the Global plugin object MyToyBox.Plugin */
trait TBPlugin { this: TBRoutes =>
object Plugin extends GlobalSettings {
override def onRouteRequest(request: RequestHeader): Option[Handler] = {
if (!isAuthorized(request)) {
Some(Action(Redirect(getLogin)))
} else {
super.onRouteRequest(request)
}
}
private def isAuthorized(request: RequestHeader): Boolean = {
// let's pretend this actually had an implementation
false
}
}
}
/** This provides the login controllers: MyToyBox.Controllers */
trait TBControllers { this: TBRoutes =>
object Controllers extends Controller {
def getLogin = Action {
Ok("In a perfect world I would be a web-page with login forms instead of a string")
}
def postLogin = Action {
Redirect("/in-a-perfect-world-id-be-a-protected-resource-or-the-toybox-login-page-with-errors")
}
}
}
}
// Now we're back in client app land. Let's use the ToyBox plugin.
import toybox.ToyBox
object MyToyBox extends ToyBox {
override def getLogin = controllers.routes.MyToyBox.Controllers.getLogin
override def postLogin = controllers.routes.MyToyBox.Controllers.postLogin
}
/* Routes look like this:
GET /login controllers.MyToyBox.Controllers.getLogin
POST /login controllers.MyToyBox.Controllers.postLogin
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment