Skip to content

Instantly share code, notes, and snippets.

@EnTeQuAk
Last active February 13, 2018 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EnTeQuAk/9327ffaa730abfb163bf45655f167e0c to your computer and use it in GitHub Desktop.
Save EnTeQuAk/9327ffaa730abfb163bf45655f167e0c to your computer and use it in GitHub Desktop.
// i18n data that get's passed to jed
let DEFAULT_I18N_DATA = {
messages: {
en: {
'This is a test': 'This is a test',
},
fr: {
'This is a test': 'C\'est un test',
},
ja: {
'This is a test': 'これはテストです',
}
}
}
// Our dummy Jed object, initialize this for real with `var jed = Jed()`
class Jed {
constructor(i18ndata, locale) {
this.options = {
locale_data: i18ndata,
}
// For our dummy only...
this.locale = locale;
}
// This is the main function that get's always called by Jed it seems, see
// https://github.com/messageformat/Jed/blob/master/jed.js#L171-L225
// for a few more details.
// So let's use this for our proxy magic :)
dcnpgettext(domain, context, singular_key, plural_key, val) {
// *VERY* simplified what happens inside Jed, obviously the real
// implementation is much more complex. for presentation only :D
return this.options.locale_data.messages[this.locale][singular_key];
}
// Actually copied from Jed
gettext(key) {
let handler = {
get(target, prop, receiver) {
if (typeof prop === 'symbol') {
return function (value) {
return this.dcnpgettext.call(this, undefined, undefined, key);
};
} else {
return Reflect.get(target, prop);
}
}
};
return new Proxy(this, handler);
}
// Needs to be set on `Jed` -> `Jed.setLocale = function() {...}`
setLocale(newLocale) {
// this.options.locale_data = require('messages/${locale}/messages.js');
this.locale = newLocale;
}
}
let i18n = new Jed(DEFAULT_I18N_DATA, 'en');
i18n.setLocale('en');
const myMessage = i18n.gettext('This is a test');
console.log('TRANSLATING STARTS HERE');
console.log('Translated:', myMessage);
i18n.setLocale('fr');
console.log('Translated:', myMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment