From d59f2d8ab235179e99e36ce2ffc8fc25d97ec347 Mon Sep 17 00:00:00 2001 From: Howy Perrin Date: Wed, 20 Dec 2017 23:07:24 +0000 Subject: [PATCH] Add non-companion way of doing validate --- .../main/scala/eu/timepit/refined/cats/validation.scala | 9 +++++++-- .../test/scala/eu/timepit/refined/cats/CatsSpec.scala | 7 +++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/modules/cats/shared/src/main/scala/eu/timepit/refined/cats/validation.scala b/modules/cats/shared/src/main/scala/eu/timepit/refined/cats/validation.scala index 83fb1b30b..5268cf6f5 100644 --- a/modules/cats/shared/src/main/scala/eu/timepit/refined/cats/validation.scala +++ b/modules/cats/shared/src/main/scala/eu/timepit/refined/cats/validation.scala @@ -2,10 +2,15 @@ package eu.timepit.refined.cats import cats.data.ValidatedNel import cats.syntax.either._ -import eu.timepit.refined.api.RefinedTypeOps +import eu.timepit.refined.api.{Refined, RefinedType, RefinedTypeOps} object validation { - implicit class CatsValidateOps[FTP, T](companion: RefinedTypeOps[FTP, T]) { + implicit class CatsValidateCompanionOps[FTP, T](companion: RefinedTypeOps[FTP, T]) { def validate(value: T): ValidatedNel[String, FTP] = companion.from(value).toValidatedNel } + implicit class CatsValidateSyntax[T](value: T) { + def validate[P]( + implicit refined: RefinedType.AuxT[T Refined P, T]): ValidatedNel[String, T Refined P] = + refined.refine(value).toValidatedNel + } } diff --git a/modules/cats/shared/src/test/scala/eu/timepit/refined/cats/CatsSpec.scala b/modules/cats/shared/src/test/scala/eu/timepit/refined/cats/CatsSpec.scala index dd3a8f995..c72d02e9a 100644 --- a/modules/cats/shared/src/test/scala/eu/timepit/refined/cats/CatsSpec.scala +++ b/modules/cats/shared/src/test/scala/eu/timepit/refined/cats/CatsSpec.scala @@ -2,6 +2,7 @@ package eu.timepit.refined.cats import cats.data.{NonEmptyList, Validated} import cats.implicits._ +import eu.timepit.refined.numeric.Positive import eu.timepit.refined.types.numeric.PosInt import org.scalacheck.Prop._ import org.scalacheck.Properties @@ -34,4 +35,10 @@ class CatsSpec extends Properties("cats") { import validation._ PosInt.validate(0) ?= Validated.Invalid(NonEmptyList("Predicate failed: (0 > 0).", Nil)) } + + property("Validate as syntax on the raw type") = secure { + import validation._ + val x = 5 + x.validate[Positive] ?= Validated.Valid(PosInt.unsafeFrom(5)) + } }