Skip to content

Instantly share code, notes, and snippets.

@lukeasrodgers
Last active August 29, 2015 14:16
Show Gist options
  • Save lukeasrodgers/981116f1483244144fa6 to your computer and use it in GitHub Desktop.
Save lukeasrodgers/981116f1483244144fa6 to your computer and use it in GitHub Desktop.
simple js factories using builder pattern
/**
* Builder pattern for factories, mimic use of FactoryGirl traits.
* usage: factories.boostedBoost({retweets: 1}).twitter().withdrawn().geo(11217).generate();
* must call `generate` as last step
* may pass options to initial method call, as well as subsequent method calls
*/
function addFactory(factoryName, config) {
// add trait function to generated Factory
function addTrait(k, Factory, config) {
Factory.prototype[k] = function() {
config.traits[k].apply(this.options, arguments);
return this;
};
}
var Factory = function(options) {
this.options = options;
};
// last step in generating an object
Factory.prototype.generate = function() {
return config.constructor.call(this);
};
for (var k in config.traits) {
if (config.traits.hasOwnProperty(k)) {
addTrait(k, Factory, config);
}
}
// attach Factory to global object
f[factoryName] = function(options) {
return new Factory(options);
};
}
var boostedBoost = {
constructor: function() {
return new Application.Models.BoostedBoost(this.options);
},
traits: {
twitter: function() {
this.network_ids = [1];
this.networks = 'Twitter';
this.original_post = {
id: 1
};
},
facebook: function() {
this.network_ids = [2];
this.networks = 'Facebook';
this.original_post = {
id: 2
};
},
withdrawn: function() {
this.withdrawn = true;
this.withdrawn_at = "2015-03-05 18:01:46 -0500";
this.allow_withdraw = false;
},
geo: function(zip) {
this.geo = zip;
}
}
};
addFactory('boostedBoost', boostedBoost);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment