Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
missing message implementation for ember-i18n to support default locale "fallback"
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
You can’t perform that action at this time.