Class: HTTPDisk::Client

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/httpdisk/client.rb

Overview

Middleware and main entry point.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Client

Returns a new instance of Client.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/httpdisk/client.rb', line 9

def initialize(app, options = {})
  options = Sloptions.parse(options) do
    _1.string :dir, default: File.join(ENV['HOME'], 'httpdisk')
    _1.integer :expires_in
    _1.boolean :force
    _1.boolean :force_errors
    _1.array :ignore_params, default: []
    _1.on :logger, type: [:boolean, Logger]
  end

  super(app, options)
  @cache = Cache.new(options)
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



7
8
9
# File 'lib/httpdisk/client.rb', line 7

def cache
  @cache
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/httpdisk/client.rb', line 7

def options
  @options
end

Instance Method Details

#call(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/httpdisk/client.rb', line 23

def call(env)
  cache_key = CacheKey.new(env, ignore_params: ignore_params)
  logger&.info("#{env.method.upcase} #{env.url} (#{cache.status(cache_key)})")

  if cached_response = read(cache_key, env)
    cached_response.env[:httpdisk] = true
    return cached_response
  end

  # miss
  perform(env).tap do |response|
    response.env[:httpdisk] = false
    write(cache_key, env, response)
  end
end

#status(env) ⇒ Object

Returns cache status for this request



40
41
42
43
44
45
46
47
48
49
# File 'lib/httpdisk/client.rb', line 40

def status(env)
  cache_key = CacheKey.new(env)
  {
    url: env.url.to_s,
    status: cache.status(cache_key).to_s,
    key: cache_key.key,
    digest: cache_key.digest,
    path: cache.diskpath(cache_key),
  }
end