Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

got model filter/where/find working properly and consistently

  • Loading branch information...
commit b769671986949065f77191b011d9c28707d8f1b4 1 parent 8d63215
@markevans authored
Showing with 53 additions and 9 deletions.
  1. +1 −0  Cakefile
  2. +11 −9 src/model.coffee
  3. +41 −0 test/src/model.coffee
View
1  Cakefile
@@ -49,6 +49,7 @@ task 'build_tests', 'Build tests from source files', ->
build [
'test/src/base'
'test/src/set'
+ 'test/src/model'
'test/src/index'
'test/src/scope'
], 'test/tests'
View
20 src/model.coffee
@@ -18,21 +18,23 @@ egg.model = (klass)->
storage.load(@, opts).done (instances) =>
@emit('load', from: storage, instances: instances, opts: opts)
+ filter: (callback)->
+ set = new egg.Set
+ @instances().forEach (instance)=> set.add instance if callback(instance)
+ set
+
where: (attrs)->
- egg.Scope.create(
- modelClass: @
- filter: (model)->
+ index = egg.Index.for(@, Object.keys(attrs))
+ if index
+ index.where(attrs)
+ else
+ @filter (model)->
for key, value of attrs
return false if model.get(key) != value
return true
- )
find: (attrs)->
- index = egg.Index.for(@, Object.keys(attrs))
- if index
- index.find(attrs)
- else
- @where(attrs).first()
+ @where(attrs).one()
findOrCreate: (attrs)->
@find(attrs) || @create(attrs: attrs)
View
41 test/src/model.coffee
@@ -0,0 +1,41 @@
+describe 'egg.model', ->
+
+ class TestModel extends egg.Base
+ @use egg.model
+
+ beforeEach ->
+ TestModel.destroyAll()
+
+ describe 'filter', ->
+ it "should return the correct models", ->
+ m1 = TestModel.create attrs: log: 'nog'
+ m2 = TestModel.create attrs: log: 'noggin'
+ m3 = TestModel.create attrs: log: 'nogules'
+ set = TestModel.filter (model) -> model.get('log').length > 4
+ expect( set.toArray() ).toEqual([m2, m3])
+
+ describe 'where', ->
+ it "should return the correct models", ->
+ m1 = TestModel.create attrs: log: 'nog'
+ m2 = TestModel.create attrs: log: 'noggin'
+ m3 = TestModel.create attrs: log: 'noggin'
+ set = TestModel.where log: 'noggin'
+ expect( set.toArray() ).toEqual([m2, m3])
+
+ it "should work when an index exists", ->
+ egg.Index.create(modelClass: TestModel, attrNames: ['log'])
+ m1 = TestModel.create attrs: log: 'nog'
+ m2 = TestModel.create attrs: log: 'noggin'
+ m3 = TestModel.create attrs: log: 'noggin'
+
+ spyOn(TestModel, 'filter')
+ set = TestModel.where log: 'noggin'
+ expect( set.toArray() ).toEqual([m2, m3])
+ expect( TestModel.filter ).not.toHaveBeenCalled()
+
+ describe 'find', ->
+ it "should return the correct model", ->
+ m1 = TestModel.create attrs: log: 'nog'
+ m2 = TestModel.create attrs: log: 'noggin'
+ m3 = TestModel.create attrs: log: 'noggin'
+ expect( TestModel.find(log: 'nog') ).toEqual(m1)
Please sign in to comment.
Something went wrong with that request. Please try again.