Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Adding several new finding methods to the model.
  • Loading branch information
dmitrig01 committed Dec 12, 2011
1 parent 1d36674 commit c6efad1
Showing 1 changed file with 45 additions and 4 deletions.
49 changes: 45 additions & 4 deletions src/model.coffee
Expand Up @@ -34,18 +34,59 @@ module.exports = class Model
values

# GENERAL METHODS
@where: (key, value, op = '=') ->
options = this
if typeof key == 'object'
options = @where.call options, k, v for k, v of key
else
options._where ?= []
options._where.push { key, value, op }
options

@limit: (limit) ->
options = this
options._limit = limit
options

@offset: (offset) ->
options = this
options._offset = offset
options

@order: (field, direction = 'ASC') ->
options = this
options._order_field = field
options._order_direction = direction
options

@_query: ->
options = this
fields = ['where', 'limit', 'offset', 'order_field', 'order_direction']
final_options = { table: @table }
final_options[field] = options['_' + field] for field of fields
final_options

@each: (callback) ->
callback ?= ->
@db.each @_query (row) ->
callback new @self row

@all: (callback) ->
callback ?= ->
@db.all @_query (rows) ->
callback (new @self row for row in rows)

@new: -> new @self

@find: (id, callback) ->
callback ?= ->
@db.query { table: @table, filters: { id: [ id ] }, limit: 1 }, (rows) =>
callback new @self rows[0]
@where('id', id).limit(1).each callback

# INSTANCE METHODS
save: (callback) ->
@db.save @_dehydrate(), callback
destroy: (callback) ->
@db.destroy @id, callback



###
For when more general methods are implemented, a way of chaining -- just need to extract proper keys at the end.
Expand Down

0 comments on commit c6efad1

Please sign in to comment.