In the rest part of my lift application I often have code like this:
object UserRest extends RestHelper {
serve("user" :: Nil prefix {
case Req("remove-item" :: itemId :: Nil, "json", PostRequest) => {
User.currentUser.map{ u =>
//doing some things and returning message
"Ready, all right."
}.getOrElse("You must be logged in to perform this operation.")
}: JValue
case Req("update-item" :: itemId :: Nil, "json", PostRequest) => {
User.currentUser.map{ u =>
//doing some things and returning message
"Ready, all right."
}.getOrElse("You must be logged in to perform this operation.")
}: JValue
}
}
As you can see for every user operation I have this piece of code:
User.currentUser.map{ u =>
//...
}.getOrElse("You must be logged in to perform this operation.")
My question is - do I have a way to put this piece of code to one place to avoid repeating it for every request?
You could write a function to handle unboxing objects for you. Something like this should help:
def unbox[A](t:Box[A])(a: A => JValue) = {
val msg = "You must be logged in to perform this operation."
t.map { u => a(u) }.getOrElse(JString(msg))
}
Then, you'd just call it like :
unbox(User.current){ u:User =>
//doing something
JString("Ready, all right.")
}