Class: Draisine::CachingClient::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/draisine/util/caching_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



6
7
8
# File 'lib/draisine/util/caching_client.rb', line 6

def initialize
  @cache = {}
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



4
5
6
# File 'lib/draisine/util/caching_client.rb', line 4

def cache
  @cache
end

Instance Method Details

#[](key) ⇒ Object



10
11
12
# File 'lib/draisine/util/caching_client.rb', line 10

def [](key)
  cache[key]
end

#[]=(key, value) ⇒ Object



18
19
20
# File 'lib/draisine/util/caching_client.rb', line 18

def []=(key, value)
  cache[key] = value
end

#add(record) ⇒ Object



22
23
24
# File 'lib/draisine/util/caching_client.rb', line 22

def add(record)
  self[record.attributes.fetch('Id')] = record
end

#add_multiple(records) ⇒ Object



26
27
28
# File 'lib/draisine/util/caching_client.rb', line 26

def add_multiple(records)
  records.each {|record| add(record) }
end

#fetch(key, &block) ⇒ Object



14
15
16
# File 'lib/draisine/util/caching_client.rb', line 14

def fetch(key, &block)
  cache.fetch(key) { cache[key] = yield }
end

#fetch_multiple(ids, &block) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/draisine/util/caching_client.rb', line 34

def fetch_multiple(ids, &block)
  if has_ids?(ids)
    cache.values_at(*ids)
  else
    yield.tap do |records|
      add_multiple(records)
    end
  end
end

#has_ids?(ids) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/draisine/util/caching_client.rb', line 30

def has_ids?(ids)
  (ids - cache.keys).empty?
end