Skip to content

Instantly share code, notes, and snippets.

@cspinetta
Created May 11, 2018 20:09
Show Gist options
  • Save cspinetta/7c0e8d55a27b4c0613e427d24ccb93e2 to your computer and use it in GitHub Desktop.
Save cspinetta/7c0e8d55a27b4c0613e427d24ccb93e2 to your computer and use it in GitHub Desktop.
pureconfig ConfigReader for parsing TimeUnit values
import pureconfig.{ConfigReader, ConvertHelpers}
import scala.concurrent.duration.TimeUnit
trait ConfigReaders {
import ConvertHelpers._
implicit val dayOfWeekReader: ConfigReader[TimeUnit] =
ConfigReader.fromString[TimeUnit](catchReadError(s => TimeUnitConverter.timeUnit(s)))
}
// Code extracted from https://github.com/pureconfig/pureconfig/blob/master/core/src/main/scala/pureconfig/DurationConvert.scala
object TimeUnitConverter {
import concurrent.duration._
private[this] val timeUnitLabels = List(
DAYS -> "d day",
HOURS -> "h hour",
MINUTES -> "min minute",
SECONDS -> "s sec second",
MILLISECONDS -> "ms milli millisecond",
MICROSECONDS -> "µs micro microsecond",
NANOSECONDS -> "ns nano nanosecond")
private[this] def words(s: String): List[String] = (s.trim split "\\s+").toList
private[this] def expandLabels(labels: String): List[String] = {
val hd :: rest = words(labels)
hd :: rest.flatMap(s => List(s, s + "s"))
}
val timeUnit: Map[String, TimeUnit] =
timeUnitLabels.flatMap { case (unit, names) => expandLabels(names) map (_ -> unit) }.toMap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment