Skip to content

Instantly share code, notes, and snippets.

@poshboytl
Forked from doitian/factories.coffee
Created November 12, 2012 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poshboytl/4059889 to your computer and use it in GitHub Desktop.
Save poshboytl/4059889 to your computer and use it in GitHub Desktop.
#>>lang=cf
@Factory = Factory = {}
ids = {}
sequences = {}
sequence = (name, callback) -> sequences[name] = callback
define = (name, defaults = {}) ->
Factory[name] = (attrs = {}) ->
result = $.extend {}, defaults, attrs
for k, v of result
if typeof v is 'function'
result[k] = v.call(result, result)
result
next = (name) ->
->
ids[name] = (ids[name] ? 0) + 1
console.log ids[name]
sequences[name]?(ids[name])
sequence 'email', (n) -> "user#{n}@exmaple.com"
one = (name) ->
->
Factory[name]()
many = (name, n = 1) ->
->
(Factory[name]() for i in [1..n])
define 'book',
name: 'Funning Book'
define 'profile',
name: 'Test'
email: next('email')
# if an attribute depends on other, must defined after
nickname: -> @name
define 'user',
profile: one('profile')
books: many('book', 3)
# SON.stringify([Factory.user(), Factory.user()], null, 2)
[
{
"profile": {
"name": "Test",
"email": "user1@exmaple.com",
"nickname": "Test"
},
"books": [ { "name": "Funning Book" }, { "name": "Funning Book" }, { "name": "Funning Book" } ]
},
{
"profile": {
"name": "Test",
"email": "user2@exmaple.com",
"nickname": "Test"
},
"books": [ { "name": "Funning Book" }, { "name": "Funning Book" }, { "name": "Funning Book" } ]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment