Created
February 23, 2018 23:18
-
-
Save toranb/e47975b7d7524195ee9115db5056d63a to your computer and use it in GitHub Desktop.
missing message implementation for ember-i18n to support default locale "fallback"
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
import { getOwner } from '@ember/application'; | |
import { typeOf } from '@ember/utils'; | |
// https://github.com/jamesarosen/ember-i18n/blob/61086238bb507922fbf458f98fd44fd6e0a24a4e/addon/utils/locale.js#L150 | |
function withFlattenedKeys(object) { | |
const result = {}; | |
Object.keys(object).forEach(function(key) { | |
var value = object[key]; | |
if (typeOf(value) === 'object') { | |
value = withFlattenedKeys(value); | |
Object.keys(value).forEach(function(suffix) { | |
result[`${key}.${suffix}`] = value[suffix]; | |
}); | |
} else { | |
result[key] = value; | |
} | |
}); | |
return result; | |
} | |
const cachedResults = {}; | |
function constructTranslationsCache(cache, factory) { | |
if (Object.keys(cache).length === 0) { | |
const translations = factory && factory.class; | |
return withFlattenedKeys(translations || {}); | |
} | |
} | |
function persistTranslations(locale, result) { | |
if (result) { | |
Object.assign(cachedResults[locale], result); | |
} | |
return cachedResults[locale]; | |
} | |
function fallbackTranslations(locale, factory) { | |
if (cachedResults[locale] === undefined) { | |
cachedResults[locale] = {}; | |
} | |
return persistTranslations(locale, constructTranslationsCache(cachedResults[locale], factory)); | |
} | |
// to help our app "fall back" to a default locale (english) | |
export default function(locale, key, context) { | |
if (locale !== 'en') { | |
const factory = getOwner(this).factoryFor('locale:en/translations'); | |
const translations = fallbackTranslations(locale, factory); | |
return translations[key]; | |
} | |
return `translation.missing: ${key}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment