Skip to content

Commit

Permalink
Merge pull request #31 from MasseGuillaume/feature/obj-getOption
Browse files Browse the repository at this point in the history
Add Conf.Obj.getOption[T](field: String)
  • Loading branch information
olafurpg authored Dec 13, 2017
2 parents 4877ae1 + f371636 commit 2aa936f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions metaconfig-core/shared/src/main/scala/metaconfig/Conf.scala
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ object Conf {
Obj(values.map {
case (k, v) => k -> f(v)
})
def getOption[T](path: String, extraNames: String*)(
implicit ev: ConfDecoder[T]): Configured[Option[T]] =
Metaconfig
.getKey(this, path +: extraNames)
.map(
value => ev.read(value).map(Some(_))
)
.getOrElse(Configured.Ok(None))
}
object Obj {
val empty = Obj()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package metaconfig

import org.scalatest.FunSuite

case class Foo(a: Option[String])
object Foo {
implicit val reader: ConfDecoder[Foo] =
ConfDecoder.instance[Foo] {
case obj: Conf.Obj =>
obj.getOption[String]("a").map(Foo(_))
}
}

class ConfOptionTest extends FunSuite {
import Conf._

test("simple") {
val conf = Obj("a" -> Str("b"))
val obtained = conf.as[Foo].get
val expected = Foo(Some("b"))
assert(obtained == expected)
}

test("missing") {
val conf = Obj()
val obtained = conf.as[Foo].get
val expected = Foo(None)
assert(obtained == expected)
}
}

0 comments on commit 2aa936f

Please sign in to comment.