Created
June 5, 2011 06:10
-
-
Save maccman/1008703 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Collection = Spine.Class.sub | |
init: (options = {}) -> | |
for key, value of options | |
@[key] = value | |
all: -> | |
@model.findAllByAttribute(@fkey, @record.id) | |
first: -> | |
@all()[0] | |
last: -> | |
values = @all() | |
values[values.length - 1] | |
find: (id) -> | |
records = @model.select (rec) => | |
rec[@fkey] == @record.id and rec.id == id | |
throw("Unknown record") unless records[0] | |
records[0] | |
select: (cb) -> | |
@model.select (rec) => | |
rec[@fkey] == @record.id and cb(rec) | |
refresh: (values) -> | |
records = @all() | |
for record in records | |
delete @model.records[record.id] | |
values = @model.fromJSON(values) | |
for value in values | |
value.newRecord = false | |
value[@fkey] = @record.id | |
@model.records[value.id] = value | |
@model.trigger("refresh") | |
create: (record) -> | |
record[@fkey] = @record.id | |
@model.create(record) | |
Instance = Spine.Class.sub | |
init: (options = {}) -> | |
for key, value of options | |
@[key] = value | |
find: -> | |
@record[@fkey] && @model.find(@record[@fkey]) | |
update: (value) -> | |
@record[@fkey] = value && value.id | |
singularize = (str) -> | |
str.replace(/s$/, '') | |
underscore = (str) -> | |
str.replace(/::/g, '/') | |
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') | |
.replace(/([a-z\d])([A-Z])/g, '$1_$2') | |
.replace(/-/g, '_') | |
.toLowerCase() | |
Spine.Model.extend | |
many: (name, model, fkey) -> | |
fkey ?= "#{underscore(this.name)}_id" | |
association = (record) -> | |
model = require(model) if typeof model is "string" | |
Collection.init( | |
name: name, model: model, | |
record: record, fkey: fkey | |
) | |
@::__defineGetter__ name, -> | |
return association(@) | |
@::__defineSetter__ name, (value) -> | |
return association(@).refresh(value) | |
belongs: (name, model) -> | |
fkey ?= "#{singularize(name)}_id" | |
association = (record) -> | |
model = require(model) if typeof model is "string" | |
Instance.init( | |
name: name, model: model, | |
record: record, fkey: fkey | |
) | |
@::__defineGetter__ name, -> | |
return association(@).find() | |
@::__defineSetter__ name, (value) -> | |
return association(@).update(value) | |
@attributes.push(fkey) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment