Created
December 16, 2012 00:52
-
-
Save anonymous/4301663 to your computer and use it in GitHub Desktop.
Some wrappers for Roise, to be able to handle "lazy" attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Factory.prototype.lazy=function(attr, callback) { | |
this._lazy.push(attr); | |
this.attrs[attr] = function(){return callback}; | |
return this; | |
}; | |
// | |
Factory.define = _.wrap(Factory.define,function(define,name,constructor){ | |
var factory = (define.bind(Factory))(name,constructor); | |
factory.name=name; | |
factory._lazy=[]; | |
Factory.builds[name] = []; | |
return factory; | |
}); | |
Factory.builds={}; | |
// | |
Factory.build = _.wrap(Factory.build,function(build,name,attrs){ | |
var result = (build.bind(Factory))(name,attrs); | |
Factory.builds[name].push(result); | |
return result; | |
}); | |
// | |
Factory.done = function(){ | |
_.each(Factory.builds,function(instances,name){ | |
var factory = Factory.factories[name]; | |
_.each(instances,function(instance){ | |
_.each(factory._lazy,function(attr){ | |
instance[attr]=(instance[attr].bind(instance))(); | |
}) | |
}); | |
}); | |
}; | |
Factory.define('pizza') | |
.sequence('id') | |
.lazy('lazy',function(){return 2}) | |
.sequence('name',function(i){return 'pizza'+i}) | |
.attr('_updated', function() { return new Date(); }) | |
.lazy('toppings', function() { | |
var toppings = Factory.builds['topping']; | |
toppings = _.first(_.shuffle(toppings),_.random(0,5)); | |
_.each(toppings,function(topping){ | |
topping.pizzas.push(this.id); | |
}.bind(this)); | |
return _.pluck(toppings,'id'); | |
}); | |
Factory.define('topping') | |
.sequence('id') | |
.attr('pizzas',function(){return []}) | |
.sequence('name', function(i) { return 'topping' + i; }); | |
var pizzas = _.map(_.range(1,100),function(){ | |
return Factory.build('pizza') | |
}); | |
var toppings = _.map(_.range(1,100),function(){ | |
return Factory.build('topping') | |
}); | |
Factory.done(); | |
console.log(pizzas,'pizzas'); | |
console.log(toppings,'toppings'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment