Skip to content

Instantly share code, notes, and snippets.

@maccman
Created May 17, 2011 12:18
Show Gist options
  • Save maccman/976370 to your computer and use it in GitHub Desktop.
Save maccman/976370 to your computer and use it in GitHub Desktop.
Types of inheritance in Spine.
(function(Spine){
var camelize = function(str){
return str.replace(/_+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
}).replace(/(^.)?/, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
};
var singularize = function(str){
return(str.replace(/s$/, ''));
};
var classify = function(str){
var result = singularize(str);
return camelize(result);
};
var underscore = function(str){
return 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();
};
var constantize = function(str){
return(eval(str.valueOf()));
};
Spine.Model.extend({
belongsTo: function(to_model, options){
if ( !options ) options = {};
var class_name = options.class_name || classify(to_model);
var foreign_key = options.foreign_key || to_model + "_id";
var primary_key = options.primary_key || "id";
var _model;
var model = function(){
return(_model || (_model = constantize(class_name)))
};
this.attributes.push(foreign_key);
this.fn["get" + class_name] = function(){
return(this[foreign_key] && model().find(this[foreign_key]));
};
this.fn["set" + class_name] = function(value){
this[foreign_key] = value && value.id;
};
},
hasMany: function(to_model, options){
if ( !options ) options = {};
var class_name = options.class_name || classify(to_model);
var foreign_key = options.foreign_key || underscore(this.className) + "_id";
var primary_key = options.primary_key || "id";
var _model;
var model = function(){
return(_model || (_model = constantize(class_name)))
};
this.fn["get" + class_name + "s"] = function(){
return(model().findAllByAttribute(foreign_key, this[primary_key]));
};
}
});
})(Spine);
Spine.Model.extend({
one: function(name, model) {
var sub;
this.attributes.push(name);
sub = function() {
if (typeof model === "string") {
return require(model);
} else {
return model;
}
};
return this.bind("init", function(record) {
if (record[name] && record[name].record) {
return;
}
record[name] = sub.init(record[name]);
return record[name].newRecord = false;
});
},
many: function(name, model) {
var sub;
this.attributes.push(name);
sub = function() {
if (typeof model === "string") {
return require(model).sub();
} else {
return model.sub();
}
};
return this.bind("init", function(record) {
var attribute;
attribute = record[name];
record[name] = sub();
if (attribute) {
return record[name].refresh(attribute.records || attribute);
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment