Class: Gin::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/gin/cache.rb

Overview

Gin::Cache is a bare-bones in-memory data store. It’s thread-safe and built for read-bound data. Reads are lock-less when no writes are queued.

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



8
9
10
11
# File 'lib/gin/cache.rb', line 8

def initialize
  @data = {}
  @lock = Gin::RWLock.new
end

Instance Method Details

#[](key) ⇒ Object

Get a value from the cache with the given key.



35
36
37
# File 'lib/gin/cache.rb', line 35

def [] key
  @lock.read_sync{ @data[key] }
end

#[]=(key, val) ⇒ Object

Set a value in the cache with the given key and value.



43
44
45
# File 'lib/gin/cache.rb', line 43

def []= key, val
  @lock.write_sync{ @data[key] = val }
end

#cache(key, value = nil, &block) ⇒ Object

Returns a cache value if it exists. Otherwise, locks and assigns the provided value or block result. Blocks get executed with the write lock to prevent redundant operations.



61
62
63
64
# File 'lib/gin/cache.rb', line 61

def cache key, value=nil, &block
  return self[key] if self.has_key?(key)
  @lock.write_sync{ @data[key] = block_given? ? yield() : value }
end

#has_key?(key) ⇒ Boolean

Check if the current key exists in the cache.

Returns:

  • (Boolean)


51
52
53
# File 'lib/gin/cache.rb', line 51

def has_key? key
  @lock.read_sync{ @data.has_key? key }
end

#write_timeoutObject

Get the write timeout when waiting for reader thread locks. See Gin::RWLock for more details.



27
28
29
# File 'lib/gin/cache.rb', line 27

def write_timeout
  @lock.write_timeout
end

#write_timeout=(sec) ⇒ Object

Set the write timeout when waiting for reader thread locks. Defaults to 0.05 sec. See Gin::RWLock for more details.



18
19
20
# File 'lib/gin/cache.rb', line 18

def write_timeout= sec
  @lock.write_timeout = sec
end