Last active
August 29, 2015 14:25
-
-
Save joecwu/410810c895dc98614083 to your computer and use it in GitHub Desktop.
Blog Scala Scalactic http://blog.joecwu.com/2015/07/scava-scala-scalaz-validation-either-scalactic.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class HttpRequest(path:String, queryStrings:Map[String,List[String]]) { | |
def getPath() : String Or String = if(path.length>0) Good(path) else Bad("path cannot be empty.") | |
def getQueryStrings() : ((List[String], Int), String) Or Every[String] = { | |
validateKeyword(queryString.get("keyword")) zip validateNumber(queryString.get("number")) zip validateGender(queryString.get("gender")) | |
} | |
def validateKeyword(value:Option[List[String]]) : List[String] Or One[String] = { | |
if(value.isDefined && value.get.length>0) Good(value.get) else Bad(One("No keyword.")) | |
} | |
def validateNumber(value:Option[List[String]]) : Int Or One[String] = { | |
try{ | |
if(value.isDefined && value.get.length>0) Good(value.get.headOption.get.toInt) else Bad(One("No Number.")) | |
}catch{ | |
case ex:Exception => Bad(One("Wrong Number.")) | |
} | |
} | |
def validateGender(value:Option[List[String]]) : String Or Every[String] = { | |
val gender = if(value.isDefined && value.get.length>0) Good(value.get.headOption.get) else Bad(One("No keyword.")) | |
gender.when(checkGenderValue) | |
} | |
def checkGenderValue(gender:String) : Validation[String] = { | |
gender.toLowerCase match { | |
case "male" | "female" => Pass | |
case _ => Fail("Wrong gender.") | |
} | |
} | |
} | |
object TestApp { | |
def run = { | |
val dummyRequest = HttpRequest( | |
"http://www.joecwu.com/user/search", | |
Map( | |
"keyword" -> List("joe") | |
) | |
) | |
dummyRequest.getPath() | |
// res: org.scalactic.Or[String,String] = Good(http://www.joecwu.com/user/search) | |
dummyRequest.getPath().map(println) | |
// http://www.joecwu.com/user/search | |
dummyRequest.getQueryStrings() | |
// res: org.scalactic.Or[((List[String], Int), String),org.scalactic.Every[String]] = Bad(Many(No Number., No keyword.)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment