Class: Wrappi::Executer::Cacher

Inherits:
Object
  • Object
show all
Defined in:
lib/wrappi/executer/cacher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoint) ⇒ Cacher

Returns a new instance of Cacher.



5
6
7
# File 'lib/wrappi/executer/cacher.rb', line 5

def initialize(endpoint)
  @endpoint = endpoint
end

Instance Attribute Details

#endpointObject (readonly)

Returns the value of attribute endpoint.



4
5
6
# File 'lib/wrappi/executer/cacher.rb', line 4

def endpoint
  @endpoint
end

Instance Method Details

#cacheObject



34
35
36
# File 'lib/wrappi/executer/cacher.rb', line 34

def cache
  endpoint.client.cache
end

#cache?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/wrappi/executer/cacher.rb', line 17

def cache?
  endpoint.client.cache && endpoint.cache && cache_allowed_verb?
end

#cache_allowed_verb?Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
# File 'lib/wrappi/executer/cacher.rb', line 21

def cache_allowed_verb?
  if [:get, :post].include?(endpoint.verb)
    true
  else
    puts "Cache is only available to no side effect requests: :get and :post" # TODO: make a warning
    false
  end
end

#cache_keyObject



38
39
40
# File 'lib/wrappi/executer/cacher.rb', line 38

def cache_key
  endpoint.cache_key
end

#cache_options(response) ⇒ Object



30
31
32
# File 'lib/wrappi/executer/cacher.rb', line 30

def cache_options(response)
  endpoint.cache_options ? endpoint.cache_options.call(response) : {}
end

#callObject



9
10
11
12
13
14
15
# File 'lib/wrappi/executer/cacher.rb', line 9

def call
  cached = cache.read(cache_key)
  return CachedResponse.new(cached) if cached
  response = yield
  cache.write(cache_key, response.to_h, cache_options(response)) if response.success?
  response
end