diff options
author | Samy Pesse <samypesse@gmail.com> | 2016-04-30 20:15:08 +0200 |
---|---|---|
committer | Samy Pesse <samypesse@gmail.com> | 2016-04-30 20:15:08 +0200 |
commit | 36b49c66c6b75515bc84dd678fd52121a313e8d2 (patch) | |
tree | bc7e0f703d4557869943ec7f9495cac7a5027d4f /lib/models/config.js | |
parent | 87db7cf1d412fa6fbd18e9a7e4f4755f2c0c5547 (diff) | |
parent | 80b8e340dadc54377ff40500f86b1de631395806 (diff) | |
download | gitbook-36b49c66c6b75515bc84dd678fd52121a313e8d2.zip gitbook-36b49c66c6b75515bc84dd678fd52121a313e8d2.tar.gz gitbook-36b49c66c6b75515bc84dd678fd52121a313e8d2.tar.bz2 |
Merge branch 'fixes'
Diffstat (limited to 'lib/models/config.js')
-rw-r--r-- | lib/models/config.js | 106 |
1 files changed, 106 insertions, 0 deletions
diff --git a/lib/models/config.js b/lib/models/config.js new file mode 100644 index 0000000..6ee03e4 --- /dev/null +++ b/lib/models/config.js @@ -0,0 +1,106 @@ +var is = require('is'); +var Immutable = require('immutable'); + +var File = require('./file'); +var configDefault = require('../constants/configDefault'); + +var Config = Immutable.Record({ + file: File(), + values: configDefault +}, 'Config'); + +Config.prototype.getFile = function() { + return this.get('file'); +}; + +Config.prototype.getValues = function() { + return this.get('values'); +}; + +/** + Return a configuration value by its key path + + @param {String} key + @return {Mixed} +*/ +Config.prototype.getValue = function(keyPath, def) { + var values = this.getValues(); + keyPath = Config.keyToKeyPath(keyPath); + + if (!values.hasIn(keyPath)) { + return Immutable.fromJS(def); + } + + return values.getIn(keyPath); +}; + +/** + Update a configuration value + + @param {String} key + @param {Mixed} value + @return {Mixed} +*/ +Config.prototype.setValue = function(keyPath, value) { + keyPath = Config.keyToKeyPath(keyPath); + + value = Immutable.fromJS(value); + + var values = this.getValues(); + values = values.setIn(keyPath, value); + + return this.set('values', values); +}; + +/** + Create a new config for a file + + @param {File} file + @param {Object} values + @returns {Config} +*/ +Config.create = function(file, values) { + return new Config({ + file: file, + values: Immutable.fromJS(values) + }); +}; + +/** + Create a new config + + @param {Object} values + @returns {Config} +*/ +Config.createWithValues = function(values) { + return new Config({ + values: Immutable.fromJS(values) + }); +}; + +/** + Update values for an existing configuration + + @param {Config} config + @param {Object} values + @returns {Config} +*/ +Config.updateValues = function(config, values) { + values = Immutable.fromJS(values); + + return config.set('values', values); +}; + + +/** + Convert a keyPath to an array of keys + + @param {String|Array} + @return {Array} +*/ +Config.keyToKeyPath = function(keyPath) { + if (is.string(keyPath)) keyPath = keyPath.split('.'); + return keyPath; +}; + +module.exports = Config; |