Skip to content

Commit

Permalink
merged #208
Browse files Browse the repository at this point in the history
  • Loading branch information
mashpie committed Feb 21, 2016
1 parent 970fcd5 commit b6e4ded
Show file tree
Hide file tree
Showing 4 changed files with 127 additions and 29 deletions.
23 changes: 15 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,17 @@ i18n.configure({
// setting of log level ERROR - default to require('debug')('i18n:error')
logErrorFn: function (msg) {
console.log('error', msg);
}
},

// object or [obj1, obj2] to bind the i18n api and current locale to - defaults to null
register: global
register: global,

// hash to specify different aliases for i18n's internal methods to apply on the request/response objects (method -> alias).
// note that this will *not* overwrite existing properties with the same name
api: {
'__': 't', //now req.__ becomes req.t
'__n': 'tn' //and req.__n can be called as req.tn
}
});
```

Expand All @@ -205,7 +212,7 @@ After this and until the cookie expires, `i18n.init()` will get the value of the

#### Some words on `register` option

Esp. when used in a cli like scriptyou won't use any `i18n.init()` to guess language settings from your user. Thus `i18n` won't bind itself to any `res` or `req` object and will work like a static module.
Esp. when used in a cli like scriptyou won't use any `i18n.init()` to guess language settings from your user. Thus `i18n` won't bind itself to any `res` or `req` object and will work like a static module.

```js
var anyObject = {};
Expand Down Expand Up @@ -346,7 +353,7 @@ __n({singular: "%s cat", plural: "%s cats", locale: "fr", count: 3}); // 3 chat
### i18n.__l()
Returns a list of translations for a given phrase in each language.
Returns a list of translations for a given phrase in each language.
```js
i18n.__l('Hello'); // --> [ 'Hallo', 'Hello' ]
Expand All @@ -367,7 +374,7 @@ app.get( __l('/:locale/products/:id?'), function (req, res) {
### i18n.__h()
Returns a hashed list of translations for a given phrase in each language.
Returns a hashed list of translations for a given phrase in each language.
```js
i18n.__h('Hello'); // --> [ { de: 'Hallo' }, { en: 'Hello' } ]
Expand Down Expand Up @@ -819,9 +826,9 @@ i18n.configure({
* __improved__: `i18n.setLocale()` and `i18n.init()` refactored to comply with most common use cases, much better test coverage and docs
* __new__: options: `autoReload`, `directoryPermissions`, `register`, `queryParameter`, read locales from filenames with empty `locales` option (#134)
* __fixed__: typos, missing and wrong docs, issues related to `i18n.setLocale()`
* 0.6.0:
* __improved__: Accept-Language header parsing to ICU, delimiters with object notation, jshint, package.json, README;
* __new__: prefix for locale files, `i18n.getLocales()`, custom logger, fallback[s];
* 0.6.0:
* __improved__: Accept-Language header parsing to ICU, delimiters with object notation, jshint, package.json, README;
* __new__: prefix for locale files, `i18n.getLocales()`, custom logger, fallback[s];
* __fixed__: typos, badges, plural (numbers), `i18n.setLocale()` for `req` _and_ `res`
* 0.5.0: feature release; added {{mustache}} parsing by #85, added "object.notation" by #110, fixed buggy req.__() implementation by #111 and closed 13 issues
* 0.4.1: stable release; merged/closed: #57, #60, #67 typo fixes; added more examples and new features: #53, #65, #66 - and some more api reference
Expand Down
57 changes: 36 additions & 21 deletions i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,20 @@ var vsprintf = require('sprintf-js').vsprintf,
Mustache = require('mustache'),
parseInterval = require('math-interval-parser').default,
locales = {},
api = [
'__',
'__n',
'__l',
'__h',
'getLocale',
'setLocale',
'getCatalog',
'getLocales',
'addLocale',
'removeLocale'
],
pathsep = path.sep, // ---> means win support will be available in node 0.8.x and above
// hash of i18n method -> alias
api = {
'__': '__',
'__n': '__n',
'__l': '__l',
'__h': '__h',
'getLocale': 'getLocale',
'setLocale': 'setLocale',
'getCatalog': 'getCatalog',
'getLocales': 'getLocales',
'addLocale': 'addLocale',
'removeLocale': 'removeLocale'
},
autoReload,
cookiename,
defaultLocale,
Expand All @@ -56,6 +57,19 @@ i18n.version = '0.7.0';

i18n.configure = function i18nConfigure(opt) {

// Provide custom API method aliases if desired
// This needs to be processed before the first call to applyAPItoObject()
if (opt.api && typeof opt.api === 'object') {
for (var method in opt.api) {
if (opt.api.hasOwnProperty(method)) {
var alias = opt.api[method];
if (typeof api[method] !== 'undefined') {
api[method] = alias;
}
}
}
}

// you may register i18n in global scope, up to you
if (typeof opt.register === 'object') {
register = opt.register;
Expand Down Expand Up @@ -297,7 +311,7 @@ i18n.__n = function i18nTranslatePlural(singular, plural, count) {
// enforce number
count = parseInt(count, 10);

// parse translation and replace all digets '%d' by `count`
// parse translation and replace all digits '%d' by `count`
// this also replaces extra strings '%%s' to parseble '%s' for next step
// simplest 2 form implementation of plural, like
// @see https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals
Expand Down Expand Up @@ -465,15 +479,16 @@ i18n.removeLocale = function i18nRemoveLocale(locale) {
var applyAPItoObject = function(object) {

// attach to itself if not provided
api.forEach(function(method) {
for (var method in api) {
if (api.hasOwnProperty(method)) {
var alias = api[method];

// be kind rewind, or better not touch anything already exiting
if (!object[method]) {
object[method] = function() {
return i18n[method].apply(object, arguments);
};
// be kind rewind, or better not touch anything already existing
if (!object[alias]) {
object[alias] = i18n[method].bind(object);
}
}
});
}

// set initial locale if not set
if (!object.locale) {
Expand Down Expand Up @@ -1016,4 +1031,4 @@ function logWarn(msg) {

function logError(msg) {
logErrorFn(msg);
}
}
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
"url": "http://github.com/mashpie/i18n-node.git"
},
"author": "Marcus Spiegel <marcus.spiegel@gmail.com>",
"contributors": [{
"name": "Adam Buczynski",
"email": "me@adambuczynski.com",
"url": "http://adambuczynski.com/"
}],
"main": "./index",
"keywords": [
"template",
Expand Down
71 changes: 71 additions & 0 deletions test/i18n.configureApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*jslint nomen: true, undef: true, sloppy: true, white: true, stupid: true, passfail: false, node: true, plusplus: true, indent: 2 */

var i18n = require('../i18n'),
should = require("should"),
fs = require('fs'),
path = require('path');

var i18nPath = 'i18n';
var i18nFilename = path.resolve(i18nPath + '.js');

function reconfigure(config) {
delete require.cache[i18nFilename];
i18n = require(i18nFilename);
i18n.configure(config);
}

describe('configure api', function() {

it('should set an alias method on the object', function() {
var customObject = {};
reconfigure({
locales: ['en', 'de'],
register: customObject,
api: {
'__': 't'
}
});
should.equal(typeof customObject.t, 'function');
should.equal(customObject.t('Hello'), 'Hello');
customObject.setLocale('de');
should.equal(customObject.t('Hello'), 'Hallo');
});

it('should work for any existing API method', function() {
var customObject = {};
reconfigure({
locales: ['en', 'de'],
register: customObject,
api: {
'getLocale': 'getLocaleAlias'
}
});
should.equal(typeof customObject.getLocaleAlias, 'function');
customObject.setLocale('de');
should.equal(customObject.getLocaleAlias(), 'de');
});

it('should ignore non existing API methods', function() {
var customObject = {};
reconfigure({
locales: ['en', 'de'],
register: customObject,
api: {
'nonExistingMethod': 'alias'
}
});
should.equal(typeof customObject.nonExistingMethod, 'undefined');
});

it('should not expose the actual API methods', function() {
var customObject = {};
reconfigure({
locales: ['en', 'de'],
register: customObject,
api: {
'__': 't'
}
});
should.equal(typeof customObject.__, 'undefined');
});
});

0 comments on commit b6e4ded

Please sign in to comment.