diff --git a/addon/messages.js b/addon/messages.js index 1bd8e7d..3a8a1ea 100644 --- a/addon/messages.js +++ b/addon/messages.js @@ -54,19 +54,52 @@ export default { }, /** - * Regex replace all placeholders with their given context + * Finds the placeholders and replace them with values + * from context depending on the availability requirements. * @method formatMessage * @param {String} message * @param {Object} context + * @param {Boolean} applyAll * @return {String} + * @private */ - formatMessage(message, context = {}) { + _formatMessage(message, context = {}, applyAll = true) { let m = message; if (isNone(m) || typeof m !== 'string') { m = get(this, 'invalid'); } - return m.replace(get(this, '_regex'), (s, attr) => get(context, attr)); + return m.replace(get(this, '_regex'), (s, attr) => { + let hasActualValue = typeof context === 'object' && context.hasOwnProperty(attr); + if (hasActualValue || applyAll) { + return get(context, attr); + } + return s; + }); + }, + + /** + * Regex replace all placeholders with their given context + * @method formatMessage + * @param {String} message + * @param {Object} context + * @return {String} + */ + formatMessage(message, context = {}) { + return this._formatMessage(message, context, true); + }, + + /** + * Regex replace placeholders with their given context + * for the keys provided by the the context. Leaves the + * unavailable keys untouched. + * @method formatMessage + * @param {String} message + * @param {Object} context + * @return {String} + */ + formatPartialMessage(message, context = {}) { + return this._formatMessage(message, context, false); }, /** diff --git a/tests/unit/validators/messages-test.js b/tests/unit/validators/messages-test.js index 87e5377..3a89661 100644 --- a/tests/unit/validators/messages-test.js +++ b/tests/unit/validators/messages-test.js @@ -24,6 +24,16 @@ test('formatMessage', function(assert) { assert.equal(messages.formatMessage('{foo} {foo} {bar} {baz}', { foo: 'a', bar: 1, baz: 'abc' }), 'a a 1 abc'); }); +test('formatPartialMessage', function(assert) { + assert.expect(3); + let context = { + description: 'This field' + }; + assert.equal(messages.formatPartialMessage(undefined, context), 'This field is invalid'); + assert.equal(messages.formatPartialMessage('{foo} is undefined'), '{foo} is undefined'); + assert.equal(messages.formatPartialMessage('{foo} {foo} {bar} {baz}', { foo: 'a', bar: 1 }), 'a a 1 {baz}'); +}); + test('getMessageFor', function(assert) { assert.expect(2); let context = {