Skip to content

Instantly share code, notes, and snippets.

@dyross
Created January 12, 2012 22:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyross/1603668 to your computer and use it in GitHub Desktop.
Save dyross/1603668 to your computer and use it in GitHub Desktop.
Scala DSL for loading properties in Play!
// Loading properties with Java API's is annoying...
// val someInt = play.configuration("some.int", 10).toInt
// val someBool = "true" == play.configuration("some.boolean", "true").toLowerCase
// This makes it nicer. It's specifically for play but can be easily changed.
object config {
def string(name: String): Proption[String] = {
Proption(Option(play.configuration(name)), name)
}
def boolean(name: String): Proption[Boolean] = {
string(name) map ("true" == _.toLowerCase)
}
def int(name: String): Proption[Int] = {
string(name) map (Integer parseInt _)
}
class ConfigurationException(message: String, arg: String) extends RuntimeException(message format arg)
}
case class Proption[T](option: Option[T], propName: String) {
def or(t: T): T = option getOrElse t
def ! : T = option match {
case Some(t) => t
case None => throw new config.ConfigurationException("mandatory prop [%s] not defined", propName)
}
def map[B](f: T => B): Proption[B] = Proption(option map f, propName)
}
// usage...
object main {
import config
import config._
val stringWithDefault = config string "string.with.default" or "default"
val mandatoryString = config string "mandatory.string" !
val intWithDefault = config int "int.with.default" or 100
val mandatoryBoolean = config boolean "mandatory.boolean" !
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment