This repository has been archived by the owner on Apr 5, 2019. It is now read-only.
forked from timoxley/rosie
-
Notifications
You must be signed in to change notification settings - Fork 2
/
rosie.js
92 lines (80 loc) · 2.28 KB
/
rosie.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var Factory = function(constructor) {
this.construct = constructor;
this.attrs = {};
this.sequences = {};
this.callbacks = [];
};
Factory.prototype = {
attr: function(attr, value) {
var callback = typeof value == 'function' ? value : function() { return value; };
this.attrs[attr] = callback;
return this;
},
sequence: function(attr, callback) {
var factory = this;
callback = callback || function(i) { return i; };
this.attrs[attr] = function() {
factory.sequences[attr] = factory.sequences[attr] || 0;
return callback(++factory.sequences[attr]);
};
return this;
},
after: function(callback) {
this.callbacks.push(callback);
return this;
},
attributes: function(attrs) {
attrs = attrs || {};
for(var attr in this.attrs) {
if(!attrs.hasOwnProperty(attr)) {
attrs[attr] = this.attrs[attr]();
}
}
return attrs;
},
build: function(attrs) {
var result = this.attributes(attrs);
return this.construct ? new this.construct(result) : result;
},
extend: function(name) {
var factory = Factory.factories[name];
// Copy the parent's constructor
if (this.construct === undefined) { this.construct = factory.construct; }
for(var attr in factory.attrs) {
if(factory.attrs.hasOwnProperty(attr)) {
this.attrs[attr] = factory.attrs[attr];
}
}
// Copy the parent's callbacks
for(var i = 0; i < factory.callbacks.length; i++) {
this.callbacks.push(factory.callbacks[i]);
}
return this;
}
};
Factory.factories = {};
Factory.define = function(name, constructor) {
var factory = new Factory(constructor);
this.factories[name] = factory;
return factory;
};
Factory.build = function(name, attrs, options) {
var obj = this.factories[name].build(attrs);
for(var i = 0; i < this.factories[name].callbacks.length; i++) {
this.factories[name].callbacks[i](obj, options);
}
return obj;
};
Factory.buildList = function(name, size, attrs, options) {
var objs = [];
for(var i = 0; i < size; i++) {
objs.push(Factory.build(name, attrs, options));
}
return objs;
};
Factory.attributes = function(name, attrs) {
return this.factories[name].attributes(attrs);
};
if (typeof exports != "undefined") {
exports.Factory = Factory;
}