Skip to content

Commit

Permalink
implement #cache_object helper, closes #1560
Browse files Browse the repository at this point in the history
  • Loading branch information
ujifgc committed Mar 13, 2014
1 parent ba1f44e commit fe59419
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions padrino-cache/lib/padrino-cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ class << self
# MyApp.cache.clear
#
def registered(app)
app.helpers Padrino::Cache::Helpers::ObjectCache
app.helpers Padrino::Cache::Helpers::CacheStore
app.helpers Padrino::Cache::Helpers::Fragment
app.helpers Padrino::Cache::Helpers::Page
Expand Down
23 changes: 23 additions & 0 deletions padrino-cache/lib/padrino-cache/helpers/cache_object.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module Padrino
module Cache
module Helpers
module ObjectCache
def cache_object(key, opts = {})
if settings.caching?
began_at = Time.now
if value = settings.cache[key.to_s]
logger.debug "GET Object", began_at, key.to_s if defined?(logger)
else
value = yield
settings.cache.store(key.to_s, value, opts)
logger.debug "SET Object", began_at, key.to_s if defined?(logger)
end
value
else
yield
end
end
end
end
end
end
21 changes: 21 additions & 0 deletions padrino-cache/test/test_padrino_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -325,4 +325,25 @@
assert_equal '{"foo":"bar"}', body
assert_match /json/, last_response.content_type
end

it 'should cache an object' do
counter = 0
mock_app do
register Padrino::Cache
enable :caching
get '/' do
result = ''
2.times do
result = cache_object 'object1' do
counter += 1
{ :foo => 'bar' }
end
end
result[:foo].to_s
end
end
get '/'
assert_equal 'bar', body
assert_equal 1, counter
end
end

0 comments on commit fe59419

Please sign in to comment.