Allow the id(s) to be redefined by subclass

This commit is contained in:
Raymond Feng 2013-10-06 21:13:52 -07:00
parent 294ebc1ccf
commit 931636eda4
2 changed files with 51 additions and 5 deletions

View File

@ -218,17 +218,29 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
subclassProperties = subclassProperties || {};
subclassSettings = subclassSettings || {};
// Check if subclass redefines the ids
var idFound = false;
for(var k in subclassProperties) {
if(subclassProperties[k].id) {
idFound = true;
break;
}
}
// Merging the properties
Object.keys(properties).forEach(function (key) {
// don't inherit the id property
if(key !== 'id' && typeof subclassProperties[key] === 'undefined') {
if(idFound && properties[key].id) {
// don't inherit id properties
return;
}
if(subclassProperties[key] === undefined) {
subclassProperties[key] = properties[key];
}
});
// Merge the settings
Object.keys(settings).forEach(function (key) {
if(typeof subclassSettings[key] === 'undefined') {
if(subclassSettings[key] === undefined) {
subclassSettings[key] = settings[key];
}
});
@ -376,7 +388,6 @@ ModelBuilder.prototype.extendModel = function (model, props) {
var definition = props[propName];
t.defineProperty(model, propName, definition);
});
t.definitions[model].build(true);
};

View File

@ -429,5 +429,40 @@ describe('Load models from json', function () {
assert(new m());
}
});
it('should be able to extend models', function (done) {
var modelBuilder = new ModelBuilder();
var User = modelBuilder.define('User', {
name: String,
bio: ModelBuilder.Text,
approved: Boolean,
joinedAt: Date,
age: Number
});
var Customer = User.extend('Customer', {customerId: {type: String, id: true}});
var customer = new Customer({name: 'Joe', age: 20, customerId: 'c01'});
customer.should.be.a('object').and.have.property('name', 'Joe');
customer.should.have.property('name', 'Joe');
customer.should.have.property('age', 20);
customer.should.have.property('customerId', 'c01');
customer.should.not.have.property('bio');
// The properties are defined at prototype level
assert.equal(Object.keys(customer).length, 0);
var count = 0;
for(var p in customer) {
if(typeof customer[p] !== 'function') {
count++;
}
}
assert.equal(count, 7); // Please note there is an injected id from User prototype
assert.equal(Object.keys(customer.toObject()).length, 6);
done(null, customer);
});
});