Permalink
Browse files

Add Scope::Model which scopes queries on a model class.

  • Loading branch information...
1 parent d991887 commit 393d5b638d92ad192462dcdfc44da94c780d44ee @alloy committed Aug 11, 2012
Showing with 68 additions and 0 deletions.
  1. +25 −0 app/scope.rb
  2. +43 −0 spec/scope_spec.rb
View
@@ -187,4 +187,29 @@ def scopeWithPredicate(predicate, sortDescriptors:sortDescriptors)
end
end
end
+
+ class Scope
+ class Model < Scope
+ def set
+ @sortDescriptors.empty? ? NSSet.setWithArray(array) : NSOrderedSet.orderedSetWithArray(array)
+ end
+
+ def array
+ error = Pointer.new(:object)
+ result = Context.current.executeFetchRequest(fetchRequest, error:error)
+ if error[0]
+ raise "Error while fetching: #{error[0].debugDescription}"
+ end
+ result
+ end
+
+ def fetchRequest
+ request = NSFetchRequest.new
+ request.entity = @target.entityDescription
+ request.predicate = @predicate
+ request.sortDescriptors = @sortDescriptors unless @sortDescriptors.empty?
+ request
+ end
+ end
+ end
end
View
@@ -261,4 +261,47 @@ def set(*objects)
request.predicate.predicateFormat.should == predicate.predicateFormat
end
end
+
+ describe Scope::Model do
+ before do
+ MotionData.setupCoreDataStackWithInMemoryStore
+
+ Article.new(:title => 'article1', :published => true)
+ @unpublishedArticle = Article.new(:title => 'article2', :published => false)
+ Article.new(:title => 'article3', :published => true)
+ end
+
+ it "returns a NSFetchRequest that represents the scope" do
+ scope = Scope::Model.alloc.initWithTarget(Article)
+
+ request = scope.fetchRequest
+ request.entity.should == Article.entityDescription
+ request.sortDescriptors.should == nil
+ request.predicate.should == nil
+
+ scope = scope.where(:published => true).sortBy(:title)
+ request = scope.fetchRequest
+ request.entity.should == Article.entityDescription
+ request.sortDescriptors.should == scope.sortDescriptors
+ request.predicate.predicateFormat.should == scope.predicate.predicateFormat
+ end
+
+ it "returns objects of the target class" do
+ scope = Scope::Model.alloc.initWithTarget(Article)
+ scope = scope.where(:published => true).sortBy(:title)
+ scope.map(&:title).should == %w{ article1 article3 }
+ end
+
+ it "returns an unordered set representation of the scope when there are no sort descriptors" do
+ scope = Scope::Model.alloc.initWithTarget(Article)
+ scope = scope.where(:published => false)
+ scope.set.should == NSSet.setWithObject(@unpublishedArticle)
+ end
+
+ it "returns an ordered set representation of the scope when there are sort descriptors" do
+ scope = Scope::Model.alloc.initWithTarget(Article)
+ scope = scope.where(:published => false).sortBy(:title)
+ scope.set.should == NSOrderedSet.orderedSetWithObject(@unpublishedArticle)
+ end
+ end
end

0 comments on commit 393d5b6

Please sign in to comment.