teddyzeenny / ember-data-factory

92 stars 8 forks source link

adding Factory.extend #11

Open bryanaka opened 10 years ago

bryanaka commented 10 years ago

I definitely miss nested factories from factory girl, so I am trying to work out a solution for some type of factory extension api.

Right now I hacked together this basic idea, but wondering if you had any input @teddyzeenny. Once I get something a bit more robust together, I'll open up a PR.

# only currently supports one level of inheritance
Factory.extend = (extendedFactory, factoryName, attrs, options) ->
  # needs proper inheritance
  defaultOptions = { modelName: extendedFactory }
  options = Em.merge(defaultOptions, options)
  newAttrs = Factory.attr(app, extendedFactory, attrs)
  Factory.define factoryName, newAttrs, options
teddyzeenny commented 10 years ago

Awesome! I would totally accept an inheritance PR.

You will probably want to merge the parent's attr during runtime instead of during definition (since you need the app which you don't have during definition).

Something like:


// Quick and untested code

Factory.extend = function(parent, name, attrs, options) {
  options = merge({ 
    modelName: definitions[parent].modelName,
    extends: parent
  }, options);
  Factory.define(name, attrs, options);
}

Factory.attr = function(app, name, props) {
  var obj = {}, def = definitions[name];
  name = normalizeName(name);
  props = props || {};
  props = toAttr(app, props);
  if (def.extends) {
    obj = merge(obj, Factory.attr(def.extends));
  }
  obj = merge(obj, definitions[name].props, props);
  obj = toAttr(app, obj);
  return obj;
};