Skip to content

Instantly share code, notes, and snippets.

@arosh
Created August 9, 2012 11:53
Show Gist options
  • Save arosh/3303574 to your computer and use it in GitHub Desktop.
Save arosh/3303574 to your computer and use it in GitHub Desktop.
extractSessionID
/**
* headerからSessionIDを抽出する
*/
def extractSessionID(header: Map[String, Set[String]]): Option[String] = {
val regex = """^JSESSIONID=(\w+);.+$""".r
val r = header.get("Set-Cookie") flatMap { cookie =>
cookie collect {
case regex(id) => id
} headOption
}
r
}
@xuwei-k
Copy link

xuwei-k commented Aug 9, 2012

collectしてからheadOptionするなら、collectFirstっていう便利なものが

def extractSessionID(header: Map[String, Set[String]]): Option[String] = {
  val regex = """^JSESSIONID=(\w+);.+$""".r

  header.get("Set-Cookie") flatMap { 
    _.collectFirst {
      case regex(id) => id
    }
  }
}

forでも書けるけど余計な変数増えるし、あまり意味ない気がする

def extractSessionID(header: Map[String, Set[String]]): Option[String] = {
  val regex = """^JSESSIONID=(\w+);.+$""".r

  for{
     cookie <- header.get("Set-Cookie")
     r <- cookie.collectFirst { case regex(id) => id }
  } yield r
}

@arosh
Copy link
Author

arosh commented Aug 9, 2012

なるほど! ありがとございます!

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