Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

render with cache now accepts a block which is executed to generate c…

…ache
  • Loading branch information...
commit 091217207a8a3e61e433ef9654a0f8d397c01b7c 1 parent cc47b82
@ryanb authored
View
10 lib/render_caching/controller_additions.rb
@@ -4,8 +4,14 @@ module ControllerAdditions
def render_with_cache(key = nil)
key ||= request.request_uri
- result = Rails.cache.fetch(key) { response.body }
- render :text => Rails.cache.read(key)
+ body = Rails.cache.read(key)
+ if body
+ render :text => body
+ else
+ yield if block_given?
+ render unless performed?
+ Rails.cache.write(key, response.body)
+ end
end
end
end
View
32 spec/render_caching/controller_additions_spec.rb
@@ -21,9 +21,10 @@ def self.cache
before(:each) do
Rails.cache.clear
@request = stub
- @response = stub
+ @response = stub(:body => '')
stubs(:request).returns(@request)
stubs(:response).returns(@response)
+ stubs(:performed?)
stubs(:render)
end
@@ -35,7 +36,6 @@ def self.cache
end
it "should read from the cache with custom passed key and render that text" do
- @request.stubs(:request_uri).returns('my_key')
Rails.cache.write('my_key', 'page content')
expects(:render).with(:text => 'page content')
render_with_cache 'my_key'
@@ -46,4 +46,32 @@ def self.cache
render_with_cache 'some_key'
Rails.cache.read('some_key').should == 'content'
end
+
+ it "should call render when not cached or rendered yet" do
+ stubs(:performed?).returns(false)
+ expects(:render).with()
+ render_with_cache 'some_key'
+ end
+
+ it "should not call render if already rendered" do
+ stubs(:performed?).returns(true)
+ stubs(:render).raises('should not be called')
+ lambda { render_with_cache 'some_key' }.should_not raise_error
+ end
+
+ it "should not call render :text if cache doesn't exist" do
+ stubs(:render).with(:text => @response.body).raises('should not be called')
+ lambda { render_with_cache 'some_key' }.should_not raise_error
+ end
+
+ it "should yield to block when not cached" do
+ pass = false
+ render_with_cache('some_key') { pass = true }
+ pass.should be_true
+ end
+
+ it "should not yield to block when cached" do
+ Rails.cache.write('some_key', 'page content')
+ render_with_cache('some_key') { violated('block was executed') }
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.