Skip to content

Instantly share code, notes, and snippets.

@julienrf
Created April 9, 2012 16:20
Show Gist options
  • Save julienrf/2344517 to your computer and use it in GitHub Desktop.
Save julienrf/2344517 to your computer and use it in GitHub Desktop.
How to implement a custom PathBindable with Play 2
def show(article: Article) = Action {
Ok(views.html.article(article))
}
case class Article(id: Long, name: String, price: Double)
implicit def articlePathBindable(implicit longBinder: PathBindable[Long]) = new PathBindable[Article] {
def bind(key: String, value: String): Either[String, Article] =
for {
id <- longBinder.bind(key, value).right
article <- Article.findById(id).toRight("Article not found").right
} yield article
def unbind(key: String, article: Article): String =
longBinder.unbind(key, article.id)
}
val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA).settings(
routesImport += "binders._"
)
override def onBadRequest(request: RequestHeader, error: String) = error match {
case "Article not found" => Redirect(controllers.routes.Articles.list)
case _ => super.onBadRequest(request, error)
}
GET /show/:article controllers.Articles.show(article: models.Article)
@scottkwalker
Copy link

In the Build.scala I was having a problem with the compile not finding routesImport. In Play 2.4 it was moved, so now you need to add import play.sbt.routes.RoutesKeys.routesImport to the Build file

@samgj18
Copy link

samgj18 commented Mar 1, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment