Class: UrlReader::FileCache

Inherits:
Object
  • Object
show all
Defined in:
lib/url_reader/file_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(cache_dir_path) ⇒ FileCache

Returns a new instance of FileCache.



2
3
4
5
# File 'lib/url_reader/file_cache.rb', line 2

def initialize(cache_dir_path)
  @cache_dir_path = cache_dir_path
  @cache = {}
end

Instance Method Details

#read_entry(key) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/url_reader/file_cache.rb', line 7

def read_entry(key)
  unless @cache.has_key?(key)
    ekey = encoded_key(key)
    hash = hash(ekey)
    file_path = File.join(@cache_dir_path, hash)
    value = nil
    if File.exist?(file_path)
      value = (decoded_value(File.open(file_path).read.strip.split("\n")
                               .select { |x| x.start_with?("#{ekey}\t") }[0].split("\t", 2)[1]) rescue nil)
    end
    @cache[key] = value
  end
  @cache[key]
end

#write_entry(key, value) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/url_reader/file_cache.rb', line 22

def write_entry(key, value)
  @cache[key] = value
  ekey = encoded_key(key)
  hash = hash(ekey)
  file_path = File.join(@cache_dir_path, hash)
  File.open(file_path, 'a') { |f| f.puts("#{ekey}\t#{encoded_value(value)}") }
  true
end