Created
January 12, 2012 22:54
-
-
Save dyross/1603668 to your computer and use it in GitHub Desktop.
Scala DSL for loading properties in Play!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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