From f2e70bdf55c4cb1a75c0342fa68c475f90695f5b Mon Sep 17 00:00:00 2001 From: Aria Stewart Date: Mon, 15 Sep 2014 15:27:42 -0700 Subject: [PATCH] Fall back on bad locale objects fixes krakenjs/file-resolver#6 --- index.js | 6 ++---- lib/util.js | 17 +++++++++++++++-- test/index.js | 22 ++++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index bd8a6a1..9dc31a2 100644 --- a/index.js +++ b/index.js @@ -47,10 +47,8 @@ var proto = { * @returns {*} */ resolve: function (name, locale) { - var match, loc; - name = name + this._ext; - loc = locale ? util.parseLangTag(locale) : this._fallback; - match = this._locate(name, loc); + var loc = util.selectLangTag(locale, this._fallback); + var match = this._locate(name + this._ext, loc); return match; } diff --git a/lib/util.js b/lib/util.js index 4cf509f..b65b6d3 100644 --- a/lib/util.js +++ b/lib/util.js @@ -27,7 +27,9 @@ var fs = require('graceful-fs'), * @param str String a language tag in the format `en-US`, `en_US`, `en`, etc. * @returns {{language: string, country: string}} */ -exports.parseLangTag = function (str) { +exports.parseLangTag = parseLangTag; + +function parseLangTag(str) { var pair, tuple; if (typeof str === 'object') { @@ -46,7 +48,7 @@ exports.parseLangTag = function (str) { } return pair; -}; +} /** @@ -79,3 +81,14 @@ exports.locate = function locate(name, root, start) { } }; + +exports.selectLangTag = function selectLangTag(primary, fallback) { + primary = parseLangTag(primary); + fallback = parseLangTag(fallback); + + if (primary.country && primary.language) { + return primary; + } else { + return fallback; + } +}; diff --git a/test/index.js b/test/index.js index d16c2f1..3f5f4c0 100644 --- a/test/index.js +++ b/test/index.js @@ -109,4 +109,26 @@ test('fileResolver', function (t) { t.equal(typeof resolvr._locate, 'function'); t.end(); }); + + t.test('resolve with a bogus locale object', function (t) { + var resolvr = fileResolver.create({root: __dirname + '/fixtures/root', ext: 'dust'}); + var info = resolvr.resolve('test', {}); + + t.equal(info.root, __dirname + '/fixtures/root/'); + t.equal(info.file, __dirname + '/fixtures/root/test.dust'); + t.equal(info.ext, 'dust'); + t.equal(info.name, 'test'); + t.end(); + }); + + t.test('fall back with a bogus locale object', function (t) { + var resolvr = fileResolver.create({root: __dirname + '/fixtures/root', ext: 'dust', fallback: 'en_US'}); + var info = resolvr.resolve('test', {}); + + t.equal(info.root, __dirname + '/fixtures/root/US/en/'); + t.equal(info.file, __dirname + '/fixtures/root/US/en/test.dust'); + t.equal(info.ext, 'dust'); + t.equal(info.name, 'test'); + t.end(); + }); });