Class: Roadie::CachedProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/roadie/cached_provider.rb

Overview

The CachedProvider wraps another provider (or ProviderList) and caches the response from it.

The default cache store is a instance-specific hash that lives for the entire duration of the instance. If you want to share hash between instances, pass your own hash-like object. Just remember to not allow this cache to grow without bounds, which a shared hash would do.

Not found assets are not cached currently, but it’s possible to extend this class in the future if there is a need for it. Remember this if you have providers with very slow failures.

The cache store must accept Stylesheet instances, and return such instances when fetched. It must respond to ‘#[name]` and `#[name]=` to retrieve and set entries, respectively. The `#[name]=` method also needs to return the instance again.

Examples:

Global cache

Application.asset_cache = Hash.new
slow_provider = MyDatabaseProvider.new(Application)
provider = Roadie::CachedProvider.new(slow_provider, Application.asset_cache)

Custom cache store

class MyRoadieMemcacheStore
  def initialize(memcache)
    @memcache = memcache
  end

  def [](path)
    css = memcache.read("assets/#{path}/css")
    if css
      name = memcache.read("assets/#{path}/name") || "cached #{path}"
      Roadie::Stylesheet.new(name, css)
    end
  end

  def []=(path, stylesheet)
    memcache.write("assets/#{path}/css", stylesheet.to_s)
    memcache.write("assets/#{path}/name", stylesheet.name)
    stylesheet # You need to return the set Stylesheet
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(upstream, cache = {}) ⇒ CachedProvider

Returns a new instance of CachedProvider.

Parameters:

  • upstream (an asset provider)

    The wrapped asset provider

  • cache (#[], #[]=) (defaults to: {})

    The cache store to use.



52
53
54
55
# File 'lib/roadie/cached_provider.rb', line 52

def initialize(upstream, cache = {})
  @upstream = upstream
  @cache = cache
end

Instance Attribute Details

#cacheObject (readonly)

The cache store used by this instance.



48
49
50
# File 'lib/roadie/cached_provider.rb', line 48

def cache
  @cache
end

Instance Method Details

#find_stylesheet(name) ⇒ Object



57
58
59
60
61
# File 'lib/roadie/cached_provider.rb', line 57

def find_stylesheet(name)
  cache_fetch(name) do
    @upstream.find_stylesheet(name)
  end
end

#find_stylesheet!(name) ⇒ Object



63
64
65
66
67
# File 'lib/roadie/cached_provider.rb', line 63

def find_stylesheet!(name)
  cache_fetch(name) do
    @upstream.find_stylesheet!(name)
  end
end