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.



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

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

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

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



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

def cache
  @cache
end

#optionsObject (readonly)

Returns the value of attribute options.



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

def options
  @options
end

Instance Method Details

#call(env) ⇒ Object



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

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

  # check cache, fallback to network
  if (response = read(cache_key, env))
    response.env[:httpdisk] = true
  else
    response = perform(env)
    response.env[:httpdisk] = false
    write(cache_key, env, response)
  end

  encode_body(response)
  response
end

#status(env) ⇒ Object

Returns cache status for this request



44
45
46
47
48
49
50
51
52
53
# File 'lib/httpdisk/client.rb', line 44

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