Created
March 27, 2014 10:48
-
-
Save gbougeard/9804835 to your computer and use it in GitHub Desktop.
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
package binders | |
import play.api.mvc._ | |
import java.net.URLEncoder | |
import play.api.data.Mapping | |
// --- Definition of a query string binder for type A using a Mapping[A] | |
object Binders { | |
implicit def mappingBinder[A](implicit mapping: Mapping[A]) = new QueryStringBindable[A] { | |
override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, A]] = { | |
val data = for { | |
(k, ps) <- params | |
if k startsWith key | |
p <- ps.headOption | |
} yield (k.drop(key.length + 1), p) | |
if (data.isEmpty) { | |
None | |
} else { | |
Some(mapping.bind(data.toMap).left.map(_ => "Unable to bind object for key '%s'".format(key))) | |
} | |
} | |
override def unbind(key: String, value: A): String = { | |
val (map, _) = mapping.unbind(value) | |
map.map { case (k, v) => key + "." + k + "=" + URLEncoder.encode(v, "utf-8") }.mkString("&") | |
} | |
} | |
} | |
case class BookingQS(custId: Option[Long], | |
hotelId: Option[Long], | |
statuses: Set[String]) | |
object BookingQS { | |
implicit val userMapping: Mapping[BookingQS] = | |
mapping( | |
"custid"->optional(number), | |
"hotelid"->optional(number), | |
"statuses"->list(text) | |
)(BookingQS.apply)(BookingQS.unapply) | |
def empty: BookingQS = { | |
new BookingQS(None, None, Set()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment