播放2.3:如何将参数传递给自定义操作

时间:2015-02-26 11:59:52

标签: scala playframework

我目前的自定义操作是

class UserRequest[A](val user: Option[models.UserProfile],
                     request: Request[A]) extends WrappedRequest[A](request)

object UserAction extends ActionBuilder[UserRequest] with ActionTransformer[Request, UserRequest] {

  def transform[A](request: Request[A]) = Future.successful {
    val user = ... get user from session
      new UserRequest(user, request)
  }
}

此外,我想将参数传递给UserAction(例如,要验证的角色)。所以在控制器中我可以这样使用它:

def admin = UserAction("admin") { Ok("granted") }

2 个答案:

答案 0 :(得分:1)

我不知道你为什么要这样做,但你可以这样做:

class UserRequest[A](val user: Option[models.UserProfile],
                 request: Request[A]) extends WrappedRequest[A](request)

object UserActionInner extends ActionBuilder[UserRequest] with ActionTransformer[Request, UserRequest] {

  def transform[A](request: Request[A]) = Future.successful {
    val user = ... get user from session
    new UserRequest(user, request)
  }

}

object UserAction {

  def apply[ A ]( str: String )( block: Request[ A ] => Future[ Result ] ) {
    // do something with your str
    // Now let UserActionInner do the job
    UserActionInner( block  )
  }

}

// Now you can use it like this.
def admin = UserAction("admin") { Ok("granted") }

答案 1 :(得分:0)

使用带有role参数的案例类而不是对象,应该会给您带来所需的效果:

case class UserAction(role: String)  extends ActionBuilder[UserRequest] with ActionTransformer[Request, UserRequest] {
  override def transform[A](request: Request[A]) = ...
}