public
Last active

Cache proxy for deferred DB-access

  • Download Gist
README.txt
1
We're deferring the execution of the database accessing code until it is really need. With this lazy evaluation we don't have to think about whether s/th is cached or not in the controller.
cache_proxy.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
class CacheProxy
# undef all methods:
instance_methods.each do |method|
undef_method(method) if method !~ /^(__)/
end
def initialize(&cache_proxy_block)
@cache_proxy_block = cache_proxy_block
end
def logger
RAILS_DEFAULT_LOGGER
end
def method_missing(method, *args, &block)
unless @cache_proxy_obj
logger.info "cache-proxy-block evaluated, triggered by ##{method}"
@cache_proxy_obj = @cache_proxy_block.call # only call the block once
end
@cache_proxy_obj.send(method, *args, &block) # delegate unknown methods to the called block
end
end
controller.rb
Ruby
1 2 3
def index
@albums = CacheProxy.new { Audio::Album.fresh_latest_songs }
end
view.haml
Haml
1 2 3
- cache 'albums' do
- unless @albums.empty?
= # show the albums

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.