Skip to content

Commit

Permalink
Fix: fallback locale should not result in loop [closes #3]
Browse files Browse the repository at this point in the history
`getFallbackLocale` returns default locale if the given locale isn't the
default one yet.  Otherwise, `null`.

Based on https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html
  • Loading branch information
alaz committed Apr 7, 2017
1 parent 71a79dd commit caf38d4
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ val email =
In SBT:

```
val i18n = "com.osinka.i18n" %% "scala-i18n" % "1.0.1"
val i18n = "com.osinka.i18n" %% "scala-i18n" % "1.0.2"
```

# Credits
Expand Down
9 changes: 6 additions & 3 deletions src/main/scala/Messages.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import java.util.{ResourceBundle, Locale}
*
* Messages are formatted with `java.text.MessageFormat`.
*/
object Messages {
trait Messages {
val FileName = "messages"
val FileExt = "txt"

Expand All @@ -35,19 +35,22 @@ object Messages {
}
}

object Messages extends Messages

// @see https://gist.github.com/alaz/1388917
// @see http://stackoverflow.com/questions/4659929/how-to-use-utf-8-in-resource-properties-with-resourcebundle
private[i18n] object UTF8BundleControl extends ResourceBundle.Control {
val Format = "properties.utf8"
val FallbackLocale = new Locale("")

override def getFormats(baseName: String): java.util.List[String] = {
import collection.JavaConverters._

Seq(Format).asJava
}

override def getFallbackLocale(baseName: String, locale: Locale) = FallbackLocale
override def getFallbackLocale(baseName: String, locale: Locale) =
if (locale == Locale.getDefault) null
else Locale.getDefault

override def newBundle(baseName: String, locale: Locale, fmt: String, loader: ClassLoader, reload: Boolean): ResourceBundle = {
import java.util.PropertyResourceBundle
Expand Down
9 changes: 9 additions & 0 deletions src/test/scala/messagesSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,14 @@ class messagesSpec extends FunSpec with Matchers {
Messages("nokey")(RU)
}
}
it("should throw if no resource") {
object NoResourceMessage extends Messages {
override val FileName = "nonexistant"
}

intercept[java.util.MissingResourceException] {
NoResourceMessage("nokey")(EN)
}
}
}
}
2 changes: 1 addition & 1 deletion version.sbt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@

version in ThisBuild := "1.0.2-SNAPSHOT"
version in ThisBuild := "1.0.2"

0 comments on commit caf38d4

Please sign in to comment.