Skip to content

Commit

Permalink
Adding groups: simple registry for resources
Browse files Browse the repository at this point in the history
  • Loading branch information
mikaa123 committed Jun 11, 2014
1 parent dea13ab commit 3b98ee8
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/catnap.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
module.exports.makeResource = require('./resource');
module.exports.makeGroup = require('./group');
32 changes: 32 additions & 0 deletions lib/group.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// A repository for resources.

var util = require('./utils'),
variadic = util.variadic,
fluent = util.fluent,
maybe = util.maybe,
extend = util.extend,
compose = util.compose;

var makeGroup = module.exports = function () {
var _resources = {};

var _group = function (r) {
var res = _resources[r];

if (!res) throw new Error('Resource ' + r + ' not found.');
return res;
};

// Adds one or many resources to the group
_group.add = fluent(maybe(variadic(function (resources) {
resources.forEach(function (r) {
if (!r._name) {
throw new Error("Can't add Resource: " + r);
}

_resources[r._name] = r;
});
})));

return _group;
};
42 changes: 42 additions & 0 deletions test/group_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
var assert = require('assert'),
should = require('should'),
sinon = require('sinon'),
makeGroup = require('../').makeGroup,
makeResource = require('../').makeResource;

describe('Group', function () {
describe('Create a group', function () {
it('Should create a new group', function () {
makeGroup().should.be.ok;
});
});

describe('Adding resources', function () {
var group;

beforeEach(function () {
group = makeGroup();
});

it('Should allow adding one or many resources', function () {
var one = makeResource('one', '/one'),
two = makeResource('two', '/two'),
three = makeResource('three', '/three');

group.add(one);
group.add(two, three);

group('one').should.eql(one);
group('two').should.eql(two);
group('three').should.eql(three);
});

it("Should throw if the Resource isn't available", function () {
[undefined, null, 'coffee'].forEach(function (v) {
assert.throws(function () {
group(v);
});
});
});
});
});

0 comments on commit 3b98ee8

Please sign in to comment.