Skip to content

Instantly share code, notes, and snippets.

@toranb
Created February 23, 2018 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toranb/e47975b7d7524195ee9115db5056d63a to your computer and use it in GitHub Desktop.
Save toranb/e47975b7d7524195ee9115db5056d63a to your computer and use it in GitHub Desktop.
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