Skip to content

Instantly share code, notes, and snippets.

@bttmly
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bttmly/52847c3ca7424ef3ed07 to your computer and use it in GitHub Desktop.
Save bttmly/52847c3ca7424ef3ed07 to your computer and use it in GitHub Desktop.
HR ORM Example
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 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;
};
@areagray
Copy link

cheers nick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment