menu
書いてる野郎
orebike@gmail.com
何をしたいかといえば、Action メソッドに書いた処理の前後に処理を割り込ませたい。 その処理を共通的に書きたい
環境: Play 2.4
割り込み処理を作る。この block(request)
というものを返すと、本来の処理を実行するということになる。
object HogeBeforeAction extends ActionBuilder[Request] { def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = { println("Hoge Before") block(request) } }
実際に割り込む。対象のコントローラーを作るが Action では無く、↑で作った。HogeBeforeAction を使う。
class Hoge extends Controller { def index = HogeBeforeAction { request => Ok("This is Hoge index") } }
これを実行すると、画面には↓のように出るが、
This is Hoge index
コンソール側(activator run した所)には↓が出ているはずだ。
Hoge Before
割り込む処理と同様に処理を差し替えることができる
Future というオブジェクトに結果をラップして返すと、本来の View と別の View を呼び出せる
import scala.concurrent.Future import play.api.mvc.Results.Ok object ShowPiyoAction extends ActionBuilder[Request] { def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = { Future.successful(Ok(views.html.piyo())) } }