diff --git a/spec/usageExamplesSpec.js b/spec/usageExamplesSpec.js index 72ebcea..67f2d19 100755 --- a/spec/usageExamplesSpec.js +++ b/spec/usageExamplesSpec.js @@ -110,6 +110,20 @@ describe('Usage Examples', function () { someRandomThing: 'value B' }); }); + it('should also be available on instantiated config objects', function () { + process.env.SOME_PREFIX__MY_VAR = 'value A'; + process.env.SOME_PREFIX__ANOTHER_VAR = 'value B'; + var actual = new JsConfig({firstValue: 'set in constructor'}); + actual.readFromObject(process.env, { + myVar: 'SOME_PREFIX__MY_VAR', + someRandomThing: 'SOME_PREFIX__ANOTHER_VAR' + }); + expect(actual.getAll()).toEqual({ + firstValue: 'set in constructor', + myVar: 'value A', + someRandomThing: 'value B' + }); + }); it('should remap string values into hierarchy', function () { process.env.SOME_PREFIX__MY_VAR = 'value A'; process.env.SOME_PREFIX__ANOTHER_VAR = 'value B'; diff --git a/src/JsConfig.js b/src/JsConfig.js index cc12cf9..dbc1b1f 100755 --- a/src/JsConfig.js +++ b/src/JsConfig.js @@ -115,29 +115,30 @@ var JsConfig = (function () { delete data[key]; } }; - } - JsConfig.readFromObject = function (obj, items) { - var missingKeys = [], output = new JsConfig(); - - function deepLoop(parent, combinedName) { - loop(parent, function (value, key) { - var name = combinedName ? combinedName + '.' : ''; - name += key; - if (typeof value === 'object') { - deepLoop(value, name); - } else { - if (obj.hasOwnProperty(value)) { - output.set(name, obj[value]); + this.readFromObject = function (obj, items) { + var self = this; + function deepLoop(parent, combinedName) { + loop(parent, function (value, key) { + var name = combinedName ? combinedName + '.' : ''; + name += key; + if (typeof value === 'object') { + deepLoop(value, name); + } else { + if (obj.hasOwnProperty(value)) { + self.set(name, obj[value]); + } } - } - }); - } + }); + } - deepLoop(items || {}); - if (missingKeys.length > 0) { - throw new Error('Missing required configuration parameter [' + missingKeys.join(',') + '].'); - } + deepLoop(items || {}); + }; + } + + JsConfig.readFromObject = function () { + var output = new JsConfig(); + output.readFromObject.apply(output, arguments); return output; };