Class: Rack::Component::Memoized

Inherits:
Rack::Component show all
Defined in:
lib/rack/component.rb

Overview

Rack::Component::Memoized is just like Component, only it caches its rendered output in memory and only rerenders when called with new arguments.

Constant Summary collapse

CACHE_SIZE =

limit to 100 keys by default to prevent leaking RAM

100

Constants inherited from Rack::Component

VERSION

Class Method Summary collapse

Methods inherited from Rack::Component

#exposures, #render

Class Method Details

.cacheRack::Component::ComponentCache

Access or instantiate a class-level cache

Returns:

  • (Rack::Component::ComponentCache)

    a threadsafe in-memory cache



53
54
55
# File 'lib/rack/component.rb', line 53

def self.cache
  @cache ||= ComponentCache.new(const_get(:CACHE_SIZE))
end

.call(*args, &block) ⇒ String, Object

Returns the cached (or computed) output of render.

Examples:

render a Memoized Component

class Expensive < Rack::Component::Memoized
  def initialize(id)
    @id = id
  end

  def work
    sleep 5
    "#{@id}"
  end

  def render
    %(<h1>#{work}</h1>)
  end
end

# first call takes five seconds
Expensive.call(id: 1) #=> <h1>1</h1>
# subsequent calls with identical args are instant
Expensive.call(id: 1) #=> <h1>1</h1>, instantly!

# subsequent calls with _different_ args take five seconds
Expensive.call(id: 2) #=> <h1>2</h1>

Returns:

  • (String, Object)

    the cached (or computed) output of render



82
83
84
# File 'lib/rack/component.rb', line 82

def self.call(*args, &block)
  memoized(*args) { super }
end

.clear_cachesObject

Clear the cache of each descendant class. Generally you’ll call this on Rack::Component::Memoized directly.

Examples:

Clear all caches:

Rack::Component::Memoized.clear_caches


101
102
103
104
105
# File 'lib/rack/component.rb', line 101

def self.clear_caches
  ObjectSpace.each_object(singleton_class) do |descendant|
    descendant.cache.flush
  end
end

.key(*args) ⇒ Integer

Returns a cache key for this component.

Returns:

  • (Integer)

    a cache key for this component



93
94
95
# File 'lib/rack/component.rb', line 93

def self.key(*args)
  args.hash
end

.memoized(*args, &miss) ⇒ Object

Check the class-level cache, set it to &miss if nil.

Returns:

  • (Object)

    the output of &miss.call



88
89
90
# File 'lib/rack/component.rb', line 88

def self.memoized(*args, &miss)
  cache.fetch(key(*args), &miss)
end