Class: WebCache

Inherits:
Object
  • Object
show all
Defined in:
lib/webcache/version.rb,
lib/webcache/response.rb,
lib/webcache/web_cache.rb

Defined Under Namespace

Classes: Response

Constant Summary collapse

VERSION =
"0.4.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir: 'cache', life: '1h') ⇒ WebCache

Returns a new instance of WebCache.



10
11
12
13
14
# File 'lib/webcache/web_cache.rb', line 10

def initialize(dir: 'cache', life: '1h')
  @dir = dir
  @life = life_to_seconds life
  @enabled = true
end

Instance Attribute Details

#dirObject

Returns the value of attribute dir.



8
9
10
# File 'lib/webcache/web_cache.rb', line 8

def dir
  @dir
end

#last_errorObject (readonly)

Returns the value of attribute last_error.



7
8
9
# File 'lib/webcache/web_cache.rb', line 7

def last_error
  @last_error
end

#lifeObject

Returns the value of attribute life.



7
8
9
# File 'lib/webcache/web_cache.rb', line 7

def life
  @life
end

Instance Method Details

#cached?(url) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
32
# File 'lib/webcache/web_cache.rb', line 29

def cached?(url)
  path = get_path url
  File.exist?(path) and !stale?(path)
end

#clear(url) ⇒ Object



46
47
48
49
# File 'lib/webcache/web_cache.rb', line 46

def clear(url)
  path = get_path url
  FileUtils.rm path if File.exist? path
end

#disableObject



42
43
44
# File 'lib/webcache/web_cache.rb', line 42

def disable
  @enabled = false
end

#enableObject



38
39
40
# File 'lib/webcache/web_cache.rb', line 38

def enable
  @enabled = true
end

#enabled?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/webcache/web_cache.rb', line 34

def enabled?
  @enabled
end

#flushObject



51
52
53
# File 'lib/webcache/web_cache.rb', line 51

def flush
  FileUtils.rm_rf dir if Dir.exist? dir
end

#get(url, force: false) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/webcache/web_cache.rb', line 16

def get(url, force: false)
  return http_get url unless enabled?

  path = get_path url
  clear url if force or stale? path

  get! path, url
end

#optionsObject



55
56
57
# File 'lib/webcache/web_cache.rb', line 55

def options
  @options ||= default_open_uri_options
end