factory-js
Version:
Building JavaScript objects inspired by rosie and factory_girl
79 lines (61 loc) • 2.13 kB
text/coffeescript
class FactoryDefinition
constructor: (name) ->
= name
= new Factory.adapter(@)
= {}
= {}
= {}
= {}
= []
adapter: (adapter) ->
= new adapter(@)
@
build: (buildType, name, attrs) ->
if [buildType]
[buildType](name, attrs)
else
attrs
after: (callback) ->
.push callback
@
attr: (attr, value) ->
[attr] = (if typeof value is 'function' then value else -> value)
@
hasMany: (attr, factoryName) ->
attr, []
(attributes, factory) ->
@[attr] = [] unless @[attr] instanceof Array
Factory.buildList(factoryName, attributes[attr]).forEach (object) =>
factory.buildAdapter['push'].call @, attr, object
@
ignore: (attr, value) ->
[attr] = (if typeof value is 'function' then value else -> value)
@
sequence: (attr, block) ->
factory = @
block = block or (i) -> i
[attr] = ->
factory.sequences[attr] = factory.sequences[attr] || 0
block.call @, ++factory.sequences[attr]
@
trait: (name, block) ->
definition = new FactoryDefinition(name)
block.call(definition) if typeof block is 'function'
[name] = definition
@
attributes: (attrs, traits) ->
attributes = Factory.hash.merge {}, attrs
ignoredAttributes = {}
traits.forEach (trait) ->
for attr of trait.attrs
attributes[attr] = trait.attrs[attr]
for attr of
attributes[attr] = [attr] unless attributes.hasOwnProperty(attr)
for attr of
ignoredAttributes[attr] = if attributes.hasOwnProperty attr then attributes[attr] else [attr]
delete attributes[attr]
Factory.hash.evaluate attributes
Factory.hash.evaluate ignoredAttributes
return withIgnored: Factory.hash.merge({}, attributes, ignoredAttributes), withoutIgnored: attributes
applyCallbacks: (result, attributes) ->
.forEach (callback) => callback.call(result, attributes, @)