Class: Opencdd::Cddal::Fetcher::NetHttp

Inherits:
Object
  • Object
show all
Defined in:
lib/opencdd/cddal/fetcher/net_http.rb

Overview

Default URL fetcher. Fetches via Net::HTTP, caches the response body to cache_dir keyed by URL hash, and supports an offline: mode that serves only cached content (used in CI to keep test runs hermetic).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir: default_cache_dir, offline: false) ⇒ NetHttp

Returns a new instance of NetHttp.



17
18
19
20
21
# File 'lib/opencdd/cddal/fetcher/net_http.rb', line 17

def initialize(cache_dir: default_cache_dir, offline: false)
  @cache_dir = cache_dir ? Pathname.new(cache_dir.to_s) : nil
  @offline = offline
  @memory_cache = {}
end

Instance Attribute Details

#cache_dirObject (readonly)

Returns the value of attribute cache_dir.



15
16
17
# File 'lib/opencdd/cddal/fetcher/net_http.rb', line 15

def cache_dir
  @cache_dir
end

#offlineObject (readonly)

Returns the value of attribute offline.



15
16
17
# File 'lib/opencdd/cddal/fetcher/net_http.rb', line 15

def offline
  @offline
end

Instance Method Details

#fetch(url) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/opencdd/cddal/fetcher/net_http.rb', line 23

def fetch(url)
  key = url.to_s
  return @memory_cache[key] if @memory_cache.key?(key)

  text = if @offline
           read_from_disk_cache(key) || raise_import_error(key)
         else
           fetch_http(key)
         end

  @memory_cache[key] = text
  write_to_disk_cache(key, text) if @cache_dir && !@offline
  text
end