storable
Version:
simple json-to-file storable objects
144 lines (128 loc) • 3.56 kB
JavaScript
// Generated by CoffeeScript 1.6.3
/* storable - simple json-to-file storable objects
c) 2013 Sebastian Glaser
Version: 0.0.1
License: GNU GPL Version 3
This file is part of storable.
storable is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
storable is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this software; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
http://www.gnu.org/licenses/gpl.html
*/
var Storable, fs,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
fs = require('fs');
module.exports = Storable = (function() {
function Storable(path, opts) {
var override;
this.path = path;
if (opts == null) {
opts = {};
}
this.save = __bind(this.save, this);
this.override = __bind(this.override, this);
this.read = __bind(this.read, this);
this.defaults = opts.defaults, override = opts.override;
null;
}
Storable.prototype.read = function(callback) {
var _read,
_this = this;
_read = function(inp) {
var k, v, _ref, _ref1;
try {
if (inp == null) {
inp = {};
}
if (_this.defaults != null) {
_ref = _this.defaults;
for (k in _ref) {
v = _ref[k];
if (inp[k] == null) {
inp[k] = v;
}
}
_ref1 = _this.defaults;
for (k in _ref1) {
v = _ref1[k];
if (typeof v === 'Number' && typeof inp[k] !== 'Number') {
inp[k] = v;
}
}
}
if (typeof override !== "undefined" && override !== null) {
for (k in override) {
v = override[k];
if (override[k] != null) {
inp[k] = v;
}
}
}
for (k in inp) {
v = inp[k];
_this[k] = v;
}
if (callback != null) {
return callback(inp);
}
} catch (_error) {}
};
fs.readFile(this.path, function(err, data) {
var e;
if (err) {
console.log('error', err);
}
try {
return _read(JSON.parse(data.toString('utf8')));
} catch (_error) {
e = _error;
console.log('error', e);
_read({});
return _this.save();
}
});
return null;
};
Storable.prototype.override = function(opts) {
var change, k, v;
if (opts == null) {
opts = {};
}
change = false;
for (k in opts) {
v = opts[k];
change = true;
this[k] = v;
}
try {
if (change) {
this.save();
}
} catch (_error) {}
return null;
};
Storable.prototype.save = function(callback) {
var k, out, v;
out = {};
for (k in this) {
v = this[k];
if (typeof v !== 'function' && k !== 'path' && k !== 'defaults') {
out[k] = v;
}
}
try {
fs.writeFile(this.path, JSON.stringify(out), callback);
} catch (_error) {}
return null;
};
return Storable;
})();