alaz/scala-i18n

[Suggestion] getOrElse method for Messages

Closed this issue · 6 comments

A bit suggestion, it will be great if you can add getOrElse method for the Messages, e.g.

val msg = Messages.getOrElse("greet", "default value")

So in case of the "greet" key is not found, I will get the default value rather than an exception being throwed.

alaz commented

The first of all, "scala-i18n" tries to reflect Play's i18n API. That's why Messages.apply signature is identical to that of Play's Messages: Messages.apply(message: String, args: Any*). Both of them have variable arguments part to supply parameters to a message.

The second, Play (and e.g. Rails) returns an internally constructed fallback message based on the key:

scala> val msg = app.injector.instanceOf[play.api.i18n.MessagesApi]
scala> msg("no.key")
res1: String = no.key

But here in "scala-i18n" I've made a decision to throw an exception when there is no key, because this small library is intended for non-UI applications mostly, e.g. generating emails. And any fallback message may remain unnoticed forever.

Does this information change your proposal?

User can always use Messages.apply if he wants get an exception.


I have other question, how we load a different message file name? e.g. I want to load dictionary*.txt instead rather than messages*.txt.

alaz commented

Please file an issue per question

alaz commented

Solution for you:

import com.osinka.i18n.{Messages => M}

object Messages extends M {
  import java.util.MissingResourceException
  import scala.util.control.Exception.failAsValue

  def getOrElse(msg: String, default: => String) =
    failAsValue(classOf[MissingResourceException])(default) { apply(msg) }
}

scala> Messages.getOrElse("greet", "default value")
res2: String = default value

Looks viable, although I prefer a solution without extending the object.

alaz commented

I don't plan it.