Class: Twitterscraper::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/twitterscraper/cache.rb

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



6
7
8
9
10
# File 'lib/twitterscraper/cache.rb', line 6

def initialize()
  @ttl = 86400 * 3 # 3 day
  @dir = 'cache'
  Dir.mkdir(@dir) unless File.exist?(@dir)
end

Instance Method Details

#cache_key(key) ⇒ Object



48
49
50
51
52
# File 'lib/twitterscraper/cache.rb', line 48

def cache_key(key)
  value = key.gsub(':', '%3A').gsub('/', '%2F').gsub('?', '%3F').gsub('=', '%3D').gsub('&', '%26')
  value = Digest::MD5.hexdigest(value) if value.length >= 100
  value
end

#delete(key) ⇒ Object



34
35
36
37
38
# File 'lib/twitterscraper/cache.rb', line 34

def delete(key)
  key = cache_key(key)
  file = File.join(@dir, key)
  File.delete(file) if File.exist?(file)
end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
# File 'lib/twitterscraper/cache.rb', line 28

def exist?(key)
  key = cache_key(key)
  file = File.join(@dir, key)
  File.exist?(file)
end

#fetch(key, &block) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/twitterscraper/cache.rb', line 40

def fetch(key, &block)
  if (value = read(key))
    value
  else
    yield.tap { |v| write(key, v) }
  end
end

#read(key) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/twitterscraper/cache.rb', line 12

def read(key)
  key = cache_key(key)
  file = File.join(@dir, key)
  entry = Entry.from_json(File.read(file))
  entry.value if entry.time > Time.now - @ttl
rescue Errno::ENOENT => e
  nil
end

#write(key, value) ⇒ Object



21
22
23
24
25
26
# File 'lib/twitterscraper/cache.rb', line 21

def write(key, value)
  key = cache_key(key)
  entry = Entry.new(key, value, Time.now)
  file = File.join(@dir, key)
  File.write(file, entry.to_json)
end