Skip to content

Instantly share code, notes, and snippets.

@evoL
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save evoL/d7ae11e8b4fce46b9e31 to your computer and use it in GitHub Desktop.

Select an option

Save evoL/d7ae11e8b4fce46b9e31 to your computer and use it in GitHub Desktop.
Underscore-based, drop-in i18n-js replacement for Rails
//= depend_on_locale
I18n = {
translations: <%= I18n.backend.send(:translations)[I18n.locale].to_json %>
};
I18n.t = (function(source) {
var interpolationRegex = /%{([^}]+)}/g;
return function(path, data) {
if (_.isUndefined(data)) data = {};
var keys = path.split('.'),
translation = _.reduce(keys, function(currentLevel, key) {
if (!_.isUndefined(currentLevel)) return currentLevel[key];
}, source);
if (!translation) return '[Missing translation: ' + path + ']';
// Handle count properly
if (!_.isUndefined(data.count) && _.isObject(translation)) {
if (data.count === 0) translation = translation.zero || translation.other;
else if (data.count === 1) translation = translation.one || translation.other;
else translation = translation.other;
}
// Perform basic interpolation
if (_.isString(translation)) {
translation = translation.replace(interpolationRegex, function(match, name) {
return data[name];
});
}
return translation;
};
})(I18n.translations);
class Sprockets::DirectiveProcessor
def process_depend_on_locale_directive
filename = "#{I18n.locale}.yml"
# Ensure that I18n is loaded
I18n.backend.send(:init_translations) unless I18n.backend.initialized?
path = File.expand_path(filename, Rails.root.join('config', 'locales'))
context.depend_on(path)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment