Skip to content

Commit

Permalink
Add Formlet.orElse
Browse files Browse the repository at this point in the history
  • Loading branch information
pbrant committed Mar 27, 2018
1 parent c261c24 commit 9e587a1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/main/scala/gov/wicourts/json/formlet/Formlet.scala
Expand Up @@ -8,7 +8,7 @@ import scalaz.NonEmptyList.nel

import scalaz.std.function._
import scalaz.std.option._
import scalaz.syntax.applicative._
import scalaz.syntax.monad._
import scalaz.syntax.monoid._
import scalaz.syntax.validation._

Expand Down Expand Up @@ -171,6 +171,20 @@ case class Formlet[M[_], I, V, E, A](run: I => M[(Validation[E, A], V)]) {
def local[X](f: X => I): Formlet[M, X, V, E, A] = Formlet(run compose f)

def contramap[X](f: X => I): Formlet[M, X, V, E, A] = local(f)

def orElse(
x: => Formlet[M, I, V, E, A]
)(
implicit M: Monad[M]
): Formlet[M, I, V, E, A] =
Formlet(i =>
this.run(i).flatMap { case (result, view) =>
result.fold(
_ => x.run(i),
j => M.point((j.success[E], view))
)
}
)
}

object Formlet {
Expand Down
9 changes: 9 additions & 0 deletions src/test/scala/gov/wicourts/json/formlet/FormsSpec.scala
Expand Up @@ -106,6 +106,15 @@ class FormsSpec extends Specification {
val results = r.obj.eval(None)
results.leftMap(_.toJson.nospaces) must_== """{"nameLOther":["Nope"]}""".failure
}

"can fail to an alternative" >> {
val failing = string("nameL", None)
.mapValidation(_ => "No way!".failureNel[Option[String]])
val good = string("nameL", None)
.mapValidation(_ => "Success!".some.successNel[String])
val results = (failing orElse good).obj.eval(None)
results must_== "Success!".some.success
}
}

"A number form" >> {
Expand Down

0 comments on commit 9e587a1

Please sign in to comment.