Last active
August 29, 2015 14:06
-
-
Save NicolaeNMV/3d375ca2e4b43aa6014f to your computer and use it in GitHub Desktop.
Check dynamically if a route path exists in play2 framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
routes: | |
GET /test controllers.Application.test(route: String) | |
GET /guessThat controllers.Application.guessIt | |
// To check: | |
/test?route=/guessIt | |
Will yield "It exists!" | |
*/ | |
object PlayUtils { | |
import play.api.Play.current | |
/** | |
* Check if a route exists or not | |
* @param requestSample - used to construct a new request with @param method and @param path | |
*/ | |
def routeExists(requestSample: Request[_], method: String, path: String): Boolean = { | |
val requestToTest = requestSample.copy(method = method, path = path) | |
Play.routes | |
.flatMap(_.handlerFor( requestToTest )) | |
.map(_ => true) | |
.getOrElse(false) | |
} | |
} | |
object Application extends Controller { | |
def index = Action { | |
Ok("Index") | |
} | |
def test(route: String) = Action { request => | |
if (PlayUtils.routeExists(request, "GET", route)) { | |
Ok("It exists !") | |
} else { | |
NotFound("Route not found") | |
} | |
} | |
def guessIt = Action { | |
Ok("test") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
shouldn't
/test?route=/guessIt
yield
"Route not found" ?
After all, its mapped to guessThat
GET /guessThat controllers.Application.guessIt