Class: Grape::Util::Cache

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Singleton
Defined in:
lib/grape/util/cache.rb

Overview

Base class for the lazily-filled lookup caches (coercers, dry-types, path parts, ...). Subclasses assign a default-block Hash to @cache in their initialize.

Lookups are synchronized: caches are written at API definition time (a params block runs when the class body is evaluated), which is not covered by the compile-time Grape::API::Instance::LOCK and can happen concurrently — e.g. parallel eager loading, or two threads autoloading different API files. A Monitor (reentrant) rather than a Mutex, because a cache miss may re-enter the same cache: building a multiple-type coercer through Types::CoercerCache builds its member coercers through Types.build_coercer, which lands in the same cache.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



22
23
24
# File 'lib/grape/util/cache.rb', line 22

def initialize
  @monitor = Monitor.new
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



20
21
22
# File 'lib/grape/util/cache.rb', line 20

def cache
  @cache
end

Instance Method Details

#[](key) ⇒ Object



26
27
28
# File 'lib/grape/util/cache.rb', line 26

def [](key)
  @monitor.synchronize { @cache[key] }
end