Skip to content

Instantly share code, notes, and snippets.

@gabu
Created May 16, 2012 03:16
Show Gist options
  • Save gabu/2707046 to your computer and use it in GitHub Desktop.
Save gabu/2707046 to your computer and use it in GitHub Desktop.
【Scala】Play 2.0 Scala で Option のネストを綺麗にしたい【初心者】
def gabu(id: String, bid: String) = Action {
Project.findOneByID(id) match {
case Some(project: Project) => Build.findOneByID(new ObjectId(bid)) match {
case Some(build: Build) =>
// etc...
Ok(views.html.gabu(build)
case None => NotFound
}
case None => NotFound
}
}
@rirakkumya
Copy link

EitherActionを使うと読みやすくなりますよ。

https://gist.github.com/2626167

上記の例だと、こんな感じです。
projectを引き継ぐように少し変えてみました。

def gabu(id: String, bid: String) = EitherAction {req =>
  id >>= {
    Project.findOneByID(_) match {
      case Some(project: Project) => project  継続
      case None => NotFound                   終了
    }
  } >>= { project => 
    Build.findOneByID(new ObjectId(bid)) match {
      case Some(build: Build) => 
        Ok(views.html.gabu(project, build)) 終了
      case None => NotFound                終了
    }
  }
}

@gabu
Copy link
Author

gabu commented May 16, 2012

うおお、こんな書き方もできるんですね。

そうなんです。サンプルだとprojectを使ってないコードになってしまっていますが、
実際のコードはprojectを引き継いで使いたいのでツッコミ非常にありがたいです。

正常系、異常系が読みやすくなっていいですね!

アドバイスありがとうございます><

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