Harbor Documentation

Harbor::ViewContext::Helpers::Cache

Cache helper that provides fragment-caching

Public Instance Methods

cache(key, ttl = 30 * 60, max_age = nil, &generator)

Caches the result of a block using the given TTL and maximum_age values. If no ttl is given, a default of 30 minutes is used. If no maximum_age value is given the item will expire after Time.now + ttl. If a maximum_age is specified, “get” requests to the cache for a given key will push the expiration time up for the item by the TTL, until Time.now + TTL is equal to or greater than the cache-insertion-time + maximum_age.

      # File lib/harbor/view_context/helpers/cache.rb, line 52
52:   def cache(key, ttl = 30 * 60, max_age = nil, &generator)
53:     store = @cache_store || Harbor::View.cache
54: 
55:     if store.nil?
56:       raise ArgumentError.new("Cache Store Not Defined.  Please set Harbor::View.cache to your desired cache store.")
57:     end
58: 
59:     content = if item = store.get(key)
60:       begin
61:         item.content
62:       rescue => e
63:         raise CacheRenderError.new(e, item)
64:       end
65:     else
66:       data = capture(&generator)
67:       store.put(key, data, ttl, max_age)
68: 
69:       data
70:     end
71: 
72:     with_buffer(generator) do |buffer|
73:       buffer << content
74:     end
75:   end