Last active
August 29, 2015 14:03
-
-
Save bttmly/52847c3ca7424ef3ed07 to your computer and use it in GitHub Desktop.
HR ORM Example
This file contains 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
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 }" |
This file contains 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
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 Model = function( data ) { | |
this.id = data.id; | |
this.name = data.name; | |
this.age = data.age; | |
this.bff = data.bff; | |
}; | |
// class methods | |
Model.find = function( id ) { | |
return new Model( query( "SELECT * FROM " + table + " WHERE id=" + id + ";" )[0] ); | |
}; | |
Model.create = function( data ) { | |
return new Model( query( "INSERT INTO " + table + " SET " + pairs( data ) + ";" ) ); | |
}; | |
Model.findAll = function() { | |
return query( "SELECT * FROM " + table + ";" ).map( function( row ) { | |
return new Model( row ); | |
}); | |
}; | |
// Prototype (instance) methods | |
Model.prototype.save = function() { | |
return query( "UPDATE TABLE " + table + " set " + pairs( this ) + " WHERE id=" + this.id + ";" ); | |
}; | |
Model.prototype.delete = function() { | |
return query( "DELETE FROM " + table + " WHERE id=" + this.id + ";" ); | |
}; | |
return Model; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cheers nick