When using Ruby, i found myself frequently making things like formatting methods to display a variety of things.
def formatDouble(dbl)
"%.2f" % dbl
end
Often these output formatters are render-specific, so defining them on the model seems kinda unflexible to me. Of course if you only have one Double to format, this is not the best/quickest way to go, but imagine you have a Snippet which has 3-4 BigDecimals to format.
class MySnippet {
def formatDouble(a: Box[BigDecimal]) = a match {
case Full(dbl) => "%.2f".format(dbl)
case _ => ""
}
def render = ".field1 *" #> formatDouble(myRecord.field1.is) &
".field2 *" #> formatDouble(myRecord.field2.is)
}
Putting a format around everything like this would be too much code for me, even for 2 lines this looks like crap to me.
What to do about it?
There is a very simple way of dealing with things, this is due to the fact that #> will only take String and NodeSeq (and a few other’s you usually don’t come to contact with), so we can work with Scala’s implicit.
class MySnippet {
implicit def formatDouble(a: Box[BigDecimal]) = a match {
case Full(dbl) => "%.2f".format(dbl)
case _ => ""
}
def render = ".field1 *" #> myRecord.field1.is &
".field2 *" #> myRecord.field2.is
}
In my (humble LOL) opinion, this looks a lot better. You can also apply this on different needs like with Tuples:
class MySnippet {
implicit def formatPrice(a: (Box[BigDecimal], String)) = a._1 match {
case Full(dbl) => "%.2f %s".format(dbl, a._2)
case _ => ""
}
def render = ".field1 *" #> (myRecord.price.is, myRecord.currency.is) &
".field2 *" #> (myRecord.shipping.is, myRecord.currency.is)
}
I hope this helps some of you folks to make your code more readable!
And yes, i admit that these example are prolly not the most advanced use cases, but you should get the idea :)
Cheers

