Skip to content

Commit

Permalink
Add fallback to language if a key is not translated in a specific reg…
Browse files Browse the repository at this point in the history
…ion of a language
  • Loading branch information
neustaTerasa authored and B3nedikt committed Aug 6, 2024
1 parent 57bb94f commit 7867be2
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,15 @@ internal class ResourcesDelegate(

private fun getStringFromRepository(id: Int): CharSequence? {

val resultLocale = getLocale() ?: return null
var resultLocale = getLocale() ?: return null

try {
val stringKey = baseResources.getResourceEntryName(id)

if(resultLocale.country.isNotEmpty() && stringRepository.strings[resultLocale]?.containsKey(stringKey) == false) {
resultLocale = Locale(resultLocale.language)
}

return stringRepository.strings[resultLocale]?.get(stringKey)
} catch (e: Resources.NotFoundException) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,29 @@ class RestringResourcesTest {
STR_VALUE shouldBeEqualTo stringValue
}

@Test
fun shouldGetStringFromRepositoryIfLanguageFallbackExists() {
val fallbackLocale = Locale("de")
val regionLocale = Locale("de", "AT")

val repository = mock<StringRepository> {
on { supportedLocales } doReturn setOf(fallbackLocale, regionLocale)
}
val restringResources = spy(RestringResources(resources, repository, context))

whenever(repository.strings).thenReturn(
mutableMapOf(
fallbackLocale to mutableMapOf(STR_KEY to STR_VALUE as CharSequence),
regionLocale to mutableMapOf()
)
)

Locale.setDefault(regionLocale)
val stringValue = restringResources.getString(STR_RES_ID)

STR_VALUE shouldBeEqualTo stringValue
}

@Test
fun shouldGetStringFromResourceIfNotExists() {
whenever(repository.strings).thenReturn(
Expand All @@ -122,6 +145,30 @@ class RestringResourcesTest {
assertEquals(expected, stringValue)
}

@Test
fun shouldGetStringFromResourceIfLanguageFallbackNotExists() {
val fallbackLocale = Locale("de")
val regionLocale = Locale("de", "AT")

val repository = mock<StringRepository> {
on { supportedLocales } doReturn setOf(fallbackLocale, regionLocale)
}
val restringResources = spy(RestringResources(resources, repository, context))

whenever(repository.strings).thenReturn(
mutableMapOf(
fallbackLocale to mutableMapOf(),
regionLocale to mutableMapOf()
)
)

Locale.setDefault(regionLocale)
val stringValue = restringResources.getString(STR_RES_ID)

val expected = resources.getText(STR_RES_ID)
assertEquals(expected, stringValue)
}

@Test
fun shouldGetStringWithParamsFromRepositoryIfExists() {
val param = "PARAM"
Expand Down

0 comments on commit 7867be2

Please sign in to comment.