Skip to content

Commit

Permalink
Adds ability to call db.load() with multiple files (closes #329)
Browse files Browse the repository at this point in the history
Files can be passed one by one as a separate argument or as Array.
Mixed arguments are possible.
The callback must be the last argument and is now optional.
  • Loading branch information
dresende committed Sep 13, 2013
1 parent c11314a commit 232bee6
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 5 deletions.
32 changes: 27 additions & 5 deletions lib/ORM.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var url = require("url");
var hat = require("hat");
var Query = require("sql-query");
var enforce = require("enforce");
var _ = require("lodash");

var Model = require("./Model").Model;
var DriverAliases = require("./Drivers/aliases");
Expand Down Expand Up @@ -254,12 +255,33 @@ ORM.prototype.close = function (cb) {

return this;
};
ORM.prototype.load = function (file, cb) {
try {
return require(Utilities.getRealPath(file))(this, cb);
} catch (ex) {
return cb(ex);
ORM.prototype.load = function () {
var files = _.flatten(Array.prototype.slice.apply(arguments));
var cb = function () {};

if (typeof files[files.length - 1] == "function") {
cb = files.pop();
}

var loadNext = function () {
if (files.length === 0) {
return cb();
}

var file = files.shift();

try {
return require(Utilities.getRealPath(file, 4))(this, function (err) {
if (err) return cb(err);

return loadNext();
});
} catch (ex) {
return cb(ex);
}
}.bind(this);

return loadNext();
};
ORM.prototype.sync = function (cb) {
var modelIds = Object.keys(this.models);
Expand Down
50 changes: 50 additions & 0 deletions test/integration/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,56 @@ describe("db.load()", function () {
});
});

describe("db.load()", function () {
var db = null;

before(function (done) {
helper.connect(function (connection) {
db = connection;

return done();
});
});

after(function () {
return db.close();
});

it("should be able to load more than one file", function (done) {
db.load("../support/spec_load_second", "../support/spec_load_third", function () {
db.models.should.have.property("person");
db.models.should.have.property("pet");

return done();
});
});
});

describe("db.load()", function () {
var db = null;

before(function (done) {
helper.connect(function (connection) {
db = connection;

return done();
});
});

after(function () {
return db.close();
});

it("should be able to load more than one file passed as Array", function (done) {
db.load([ "../support/spec_load_second", "../support/spec_load_third" ], function () {
db.models.should.have.property("person");
db.models.should.have.property("pet");

return done();
});
});
});

describe("db.serial()", function () {
var db = null;

Expand Down

0 comments on commit 232bee6

Please sign in to comment.