Skip to content
This repository has been archived by the owner on Jun 19, 2021. It is now read-only.

Commit

Permalink
Validator.context/2 can now set multiple contexts at once
Browse files Browse the repository at this point in the history
+ Add Validator.prototype.getContexts() to get the defined contexts
  • Loading branch information
mendezcode committed Feb 14, 2015
1 parent 5069e95 commit a74cf6b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
24 changes: 23 additions & 1 deletion lib/validator.js
Expand Up @@ -27,7 +27,7 @@ function Validator(config) {
// Options
this.config = protos.extend({
cleanup: true
}, config);
}, config || {});

// Set context
Object.defineProperty(this, '__context', {
Expand Down Expand Up @@ -133,11 +133,33 @@ Validator.prototype.context = function(context, func) {
}
} else if (context instanceof Function) {
context.call(this);
} else if (typeof context === 'object') {
for (var key in context) {
if (context.hasOwnProperty(key)) {
if (context[key] instanceof Validator) {
this.__context[key] = context[key];
} else if (context[key] instanceof Function) {
instance = new Validator();
this.__context[key] = instance;
context[key].call(instance, instance);
}
}
}
return this;
} else {
return this.__context[context];
}
}

/**
Gets the defined contexts in instance
*/

Validator.prototype.getContexts = function() {
return this.__context;
}

/**
Adds a validation rule to the validator instance
Expand Down
45 changes: 44 additions & 1 deletion test/unit/validator.js
Expand Up @@ -660,7 +660,7 @@ vows.describe('lib/validator.js').addBatch({
assert.strictEqual(instance, validator);
},

'Properly sets multiple contexts': function() {
'Properly sets context aliases': function() {

var instance, validator = app.validator();

Expand All @@ -676,6 +676,49 @@ vows.describe('lib/validator.js').addBatch({
assert.strictEqual(bar, instance);
assert.strictEqual(baz, instance);

},

'Properly gets/sets multiple contexts': function() {

var customInstance = app.validator();
var validator = app.validator();

var one, two;

validator.context({

one: function(v) {
if (this === v) {
one = this;
}
},

two: function(v) {
if (this === v) {
two = this;
}
},

three: customInstance,

four: 4, // Should be ignored

five: {} // Should be ignored

});

// Checking multiple contexts being set
assert.strictEqual(one, validator.context('one'));
assert.strictEqual(two, validator.context('two'));
assert.strictEqual(customInstance, validator.context('three'));

// Invalid properties in context object are ignored
assert.isUndefined(validator.context('four'));
assert.isUndefined(validator.context('five'));

// Validator.prototype.getContexts() returns the internal context representation
assert.strictEqual(validator.__context, validator.getContexts());

}

}).addBatch({
Expand Down

0 comments on commit a74cf6b

Please sign in to comment.