Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ConfigValue#orNone #107

Merged
merged 1 commit into from
Feb 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions modules/core/shared/src/main/scala/ciris/ConfigValue.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,28 @@ abstract class ConfigValue[F[_]: Apply, V] {
}
}

/**
* If the value of this [[ConfigValue]] is available, wraps the
* value in a `Some`; otherwise, uses `None` as the value, and
* discards the [[ConfigError]]. This function is particularly
* useful when combined with [[orElse]] as in the example.
*
* @return a new [[ConfigValue]]
* @example {{{
* scala> env[String]("API_KEY").
* | orElse(prop[String]("api.key")).
* | orNone
* res0: ConfigValue[api.Id,Option[String]] = ConfigValue(Right(None))
* }}}
*/
final def orNone: ConfigValue[F, Option[V]] =
ConfigValue.applyF[F, Option[V]] {
this.value.map {
case Right(v) => Right(Some(v))
case Left(_) => Right(None)
}
}

private[ciris] final def append[A](next: ConfigValue[F, A]): ConfigValue2[F, V, A] = {
new ConfigValue2((this.value product next.value).map {
case (Right(v), Right(a)) => Right((v, a))
Expand Down
14 changes: 14 additions & 0 deletions tests/shared/src/test/scala/ciris/ConfigValueSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,19 @@ final class ConfigValueSpec extends PropertySpec {
ConfigValue.applyF[Id, Int](right(123)).toString shouldBe "ConfigValue(Right(123))"
}
}

"using orNone" should {
"wrap existing values in Some" in {
nonExistingEntry
.orElse(existingEntry("value"))
.orNone.value shouldBe Right(Some("value"))
}

"discard errors and return None" in {
nonExistingEntry
.orElse(nonExistingEntry)
.orNone.value shouldBe Right(None)
}
}
}
}