Class: Codeforces::Viewer::Cacher

Inherits:
Object
  • Object
show all
Defined in:
lib/codeforces/viewer/cacher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enabled = true, cache_dir = DEFAULT_CACHE_DIR) ⇒ Cacher

Returns a new instance of Cacher.



13
14
15
16
17
18
19
20
# File 'lib/codeforces/viewer/cacher.rb', line 13

def initialize(enabled = true, cache_dir = DEFAULT_CACHE_DIR)
  @option = {}
  @option[:enabled] = enabled
  if @option[:enabled]
    @option[:cache_dir] = File.expand_path cache_dir
    FileUtils.mkdir_p @option[:cache_dir]
  end
end

Instance Attribute Details

#optionObject

Returns the value of attribute option.



11
12
13
# File 'lib/codeforces/viewer/cacher.rb', line 11

def option
  @option
end

Instance Method Details

#get_url(url) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/codeforces/viewer/cacher.rb', line 22

def get_url(url)
  file_path = "#{@option[:cache_dir]}/#{Digest::MD5.hexdigest url}"
  if @option[:enabled] && File.exists?(file_path)
    File.read file_path
  else
    body = Net::HTTP.get URI.parse url
    if @option[:enabled]
      FileUtils.touch file_path
      File.write file_path, body
    end
    body
  end
end