Skip to content

Commit

Permalink
Add messageFallback property
Browse files Browse the repository at this point in the history
  • Loading branch information
spyric committed May 8, 2017
1 parent 0512672 commit 9f5fcca
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
40 changes: 38 additions & 2 deletions src/lang.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
this.locale = options.locale || inferLocale() || defaults.locale;
this.fallback = options.fallback;
this.messages = options.messages;
this.messageFallback = options.messageFallback;
};

// Methods //
Expand Down Expand Up @@ -111,6 +112,26 @@
this.fallback = fallback;
};

/**
* Get the message fallback closure.
*
* @return closure|null
*/
Lang.prototype.getMessageFallback = function() {
return this.messageFallback;
};

/**
* Set the message fallback closure.
*
* @param messageFallback {string} The messageFallback closure.
*
* @return void
*/
Lang.prototype.setMessageFallback = function(messageFallback) {
this.messageFallback = messageFallback;
};

/**
* This method act as an alias to get() method.
*
Expand Down Expand Up @@ -138,12 +159,12 @@
*/
Lang.prototype.get = function(key, replacements, locale) {
if (!this.has(key)) {
return key;
return this.printKey(key);
}

var message = this._getMessage(key, locale);
if (message === null) {
return key;
return this.printKey(key);
}

if (replacements) {
Expand All @@ -153,6 +174,21 @@
return message;
};

/**
* Call message fallback and return key
*
* @param key {string} The key of the message.
*
* @return {string} The given key.
*/
Lang.prototype.printKey = function(key){
if(this.messageFallback !== undefined) {
this.messageFallback(key);
}

return key;
}

/**
* This method act as an alias to get() method.
*
Expand Down
7 changes: 7 additions & 0 deletions test/spec/lang_get_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ describe('The lang.get() method', function () {
expect(lang.get(null)).toBe(null);
});

it('should call massage fallback closure and return the passed key when not found', function () {
var test = '';
lang.setMessageFallback(function(key){ test = key });
expect(lang.get('foo.bar')).toBe('foo.bar');
expect(test).toBe('foo.bar');
});

it('should return the expected message', function () {
expect(lang.get('messages.home')).toBe('Home');
});
Expand Down

0 comments on commit 9f5fcca

Please sign in to comment.