Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add messageFallback property #44

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dist/lang.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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