Skip to content

Instantly share code, notes, and snippets.

@phillipalexander
Forked from bttmly/makeORMClass.coffee
Created June 29, 2014 04:05
Show Gist options
  • Save phillipalexander/3147b4533b74bb5a6a34 to your computer and use it in GitHub Desktop.
Save phillipalexander/3147b4533b74bb5a6a34 to your computer and use it in GitHub Desktop.
pairs = ( obj ) ->
arr = []
for own key, val of obj when key isnt "id"
arr.push "#{ key }=#{ val}"
arr.join ","
makeORMClass = ( table ) ->
# CoffeeScript syntactic sugar for class creation.
class Model
# Constructor function
constructor: ( obj ) ->
{ @id, @name, @age, @bff } = obj
# Class methods
@find: ( id ) ->
new Model query( "SELECT * FROM #{ table } WHERE id=#{ id };" )[0]
@create: ( data ) ->
new Model query( "INSERT INTO #{ table } SET #{ pairs data };" )[0]
@findAll: ->
new Model row for row in query "SELECT * FROM #{ table } ;"
# Prototype (instance) methods
save: ->
query "UPDATE TABLE #{ table } set #{ pairs @ } WHERE id=#{ @id }"
delete: ->
query "DELETE TABLE #{ table } WHERE id=#{ @id }"
var pairs = function( obj ){
var arr = [];
var key;
for ( key in obj ) {
if ( key !== "id" ) {
arr.push( key + "=" obj[key] );
}
}
return arr.join( "," );
}
var makeORMClass = function( table ) {
// constructor function
var Class = function( data ) {
this.id = data.id;
this.name = data.name;
this.age = data.age;
this.bff = data.bff;
};
// class methods
Class.find = function( id ) {
return new Class( query( "SELECT * FROM " + table + " WHERE id=" + id + ";" )[0] );
};
Class.create = function( data ) {
return new Class( query( "INSERT INTO " + table + " SET " + pairs( data ) + ";" ) );
};
Class.findAll = function() {
return query( "SELECT * FROM " + table + ";" ).map( function( row ) {
return new Class( row );
});
};
// Prototype (instance) methods
Class.prototype.save = function() {
return query( "UPDATE TABLE " + table + " set " + pairs( this ) + " WHERE id=" + this.id + ";" );
};
Class.prototype.delete = function() {
return query( "DELETE FROM " + table + " WHERE id=" + this.id + ";" );
};
return Class;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment