public
Last active

ormnomnom rewrite.

  • Download Gist
example.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
{models, Author, Book} = require './models'
{connection} = require 'ormnomnom'
 
 
conn = connection.Connection.get_connection 'default'
 
models.db_creation 'default', yes, ->
create_book = Book.objects.create
author:Author.objects.get_or_create {first_name:'Cormac', last_name:'McCarthy', slug:'cormac-mccarthy'}
title:'Blood Meridian'
slug:'blood-meridian'
desc:'A book about violence and cowboys.'
 
# `create_book` is an EventEmitter AND a function.
create_book.on 'data', (book)->
console.log "Created #{book} with id of #{book.pk}"
 
# likewise, so is `book.author()`.
book.author() (err, author)->
console.log "using #{author} with id of #{author.pk}"
 
 
# you can join across foreign keys in filters
books = Book.objects.filter
author__first_name:'Cormac'
 
# for each book returned, log its name.
books.each (book)->
console.log "Got #{book}, #{book.pk}"
 
# we're done here.
books conn.close.bind conn
index.js
JavaScript
1 2
require('coffee-script');
require('./example');
models.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
{models} = require 'ormnomnom'
 
models.configure 'default',
backend:'ormnomnom/lib/backends/postgres'
name:'testdb'
 
exports.models =
models.namespace 'authors', (ns)->
Author = ns.create 'Author'
 
Author.schema
first_name:models.CharField {max_length:255}
last_name:models.CharField {max_length:255}
slug:models.CharField {max_length:255}
 
Author.meta
order_by:['last_name', 'first_name']
 
Author::toString =->
"<Author: \"#{@get_full_name()}\">"
 
Author::get_full_name = ->
[@first_name, @last_name].join ' '
 
Book = ns.create 'Book'
 
Book.schema
author: models.ForeignKey Author
title: models.CharField {max_length:255}
slug: models.CharField {max_length:255}
desc: models.TextField
 
Book::toString =->
"<Book: \"#{@title}\">"
 
exports.Author = Author
exports.Book = Book
output.sh
Shell
1 2 3 4 5 6 7 8 9
$ node index.js
Created <Book: "Blood Meridian"> with id of 6
using <Author: "Cormac McCarthy"> with id of 1
Got <Book: "Blood Meridian">, 1
Got <Book: "Blood Meridian">, 2
Got <Book: "Blood Meridian">, 3
Got <Book: "Blood Meridian">, 4
Got <Book: "Blood Meridian">, 5
Got <Book: "Blood Meridian">, 6

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.