Skip to content

Commit

Permalink
Add the ability to "resolve" values
Browse files Browse the repository at this point in the history
closes #10
  • Loading branch information
dougwilson committed Nov 10, 2014
1 parent 0f1010e commit ddf0aa4
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 2 deletions.
15 changes: 15 additions & 0 deletions Readme.md
Expand Up @@ -23,3 +23,18 @@ If your objective is to simply require all .js and .json files in a directory yo
``` js
var libs = require('require-all')(__dirname + '/lib');
```

## Constructed object usage

If your directory contains files that all export constructors, you can require them all and automatically construct the objects using `resolve`:

```js
var controllers = require('require-all')({
dirname : __dirname + '/controllers',
filter : /(.+Controller)\.js$/,
excludeDirs : /^\.(git|svn)$/,
resolve : function (Controller) {
return new Controller();
}
});
```
10 changes: 8 additions & 2 deletions index.js
Expand Up @@ -11,6 +11,7 @@ module.exports = function requireAll(options) {

var files = fs.readdirSync(options.dirname);
var modules = {};
var resolve = options.resolve || identity;

function excludeDirectory(dirname) {
return options.excludeDirs && dirname.match(options.excludeDirs);
Expand All @@ -25,16 +26,21 @@ module.exports = function requireAll(options) {
modules[file] = requireAll({
dirname: filepath,
filter: options.filter,
excludeDirs: options.excludeDirs
excludeDirs: options.excludeDirs,
resolve: resolve
});

} else {
var match = file.match(options.filter);
if (!match) return;

modules[match[1]] = require(filepath);
modules[match[1]] = resolve(require(filepath));
}
});

return modules;
};

function identity(val) {
return val;
}
3 changes: 3 additions & 0 deletions test/resolved/onearg.js
@@ -0,0 +1,3 @@
module.exports = function (arg1, arg2) {
return arg1;
}
3 changes: 3 additions & 0 deletions test/resolved/twoargs.js
@@ -0,0 +1,3 @@
module.exports = function (arg1, arg2) {
return arg2;
}
11 changes: 11 additions & 0 deletions test/test.js
Expand Up @@ -80,3 +80,14 @@ var excludedSvnAndSub = requireAll({
assert.equal(excludedSvnAndSub['.svn'], undefined);
assert.ok(excludedSvnAndSub.root);
assert.equal(excludedSvnAndSub.sub, undefined);

var resolvedValues = requireAll({
dirname: __dirname + '/resolved',
filter: /(.+)\.js$/,
resolve: function (fn) {
return fn('arg1', 'arg2');
}
});

assert.equal(resolvedValues.onearg, 'arg1');
assert.equal(resolvedValues.twoargs, 'arg2');

0 comments on commit ddf0aa4

Please sign in to comment.