Skip to content
Browse files

Add ability to cache document.

  • Loading branch information...
1 parent dcca932 commit 59a535112263caad18a6def1efe3bf7b5532eb3f @jnunemaker committed Aug 8, 2012
View
30 lib/flipper/adapters/mongo_single_document.rb
@@ -11,13 +11,43 @@ class MongoSingleDocument
def initialize(collection, options = {})
@collection = collection
@options = options
+ @document_cache = false
end
def_delegators :document, :read, :write, :delete, :set_members, :set_add, :set_delete
+ def using_document_cache?
+ @document_cache == true
+ end
+
+ def document_cache=(value)
+ reset_document_cache
+ @document_cache = value
+ end
+
+ def use_document_cache(&block)
+ original = @document_cache
+ @document_cache = true
+ yield
+ ensure
+ @document_cache = original
+ end
+
+ def reset_document_cache
+ @document = nil
+ end
+
private
def document
+ if @document_cache == true
+ @document ||= fresh_document
+ else
+ fresh_document
+ end
+ end
+
+ def fresh_document
Document.new(@collection, :id => @options[:id])
end
end
View
56 spec/flipper/adapters/mongo_single_document_spec.rb
@@ -35,5 +35,59 @@ def write_key(key, value)
collection.update criteria, updates, options
end
- it_should_behave_like 'a flipper adapter'
+ context "with cache" do
+ before do
+ subject.document_cache = true
+ end
+
+ it_should_behave_like 'a flipper adapter'
+
+ it "should only query mongo once until reloaded" do
+ collection.should_receive(:find_one).with(criteria).once.and_return({})
+ subject.read('foo')
+ subject.read('foo')
+ subject.read('foo')
+ subject.set_members('users')
+
+ subject.reset_document_cache
+
+ collection.should_receive(:find_one).with(criteria).once.and_return({})
+ subject.read('foo')
+ subject.read('foo')
+ subject.set_members('users')
+ end
+ end
+
+ context "without cache" do
+ before do
+ subject.document_cache = false
+ end
+
+ it_should_behave_like 'a flipper adapter'
+ end
+
+ describe "#use_document_cache" do
+ it "turns cache on for block and restores to original after block" do
+ subject.using_document_cache?.should be_false
+ subject.use_document_cache do
+ subject.using_document_cache?.should be_true
+ end
+ subject.using_document_cache?.should be_false
+ end
+ end
+
+ describe "#document_cache=" do
+ it "sets document cache" do
+ subject.document_cache = true
+ subject.using_document_cache?.should be_true
+
+ subject.document_cache = false
+ subject.using_document_cache?.should be_false
+ end
+
+ it "resets cached document" do
+ subject.should_receive(:reset_document_cache)
+ subject.document_cache = true
+ end
+ end
end

0 comments on commit 59a5351

Please sign in to comment.
Something went wrong with that request. Please try again.