Class: HashCache

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opt = {}) ⇒ HashCache

Returns a new instance of HashCache.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/hashcache.rb', line 11

def initialize(opt={})
  o = {size: 5, file_cache: false, file_path: '/tmp'}.merge(opt)
  @size = o[:size]
  @file_cache = o[:file_cache]
  @file_path = o[:file_path]
  @h = {}
  
  def @h.expired?(item)
    expiry_time = self.fetch(item)[:expiry_time]
    return false unless expiry_time
    expiry_time < Time.now
  end
  
end

Instance Attribute Details

#file_cacheObject

Returns the value of attribute file_cache.



9
10
11
# File 'lib/hashcache.rb', line 9

def file_cache
  @file_cache
end

#file_pathObject

Returns the value of attribute file_path.



9
10
11
# File 'lib/hashcache.rb', line 9

def file_path
  @file_path
end

#sizeObject

Returns the value of attribute size.



9
10
11
# File 'lib/hashcache.rb', line 9

def size
  @size
end

Class Method Details

.expired?(item) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
# File 'lib/hashcache.rb', line 18

def @h.expired?(item)
  expiry_time = self.fetch(item)[:expiry_time]
  return false unless expiry_time
  expiry_time < Time.now
end

Instance Method Details

#delete(item) ⇒ Object



65
66
67
# File 'lib/hashcache.rb', line 65

def delete(item)
  @h.delete item    
end

#read(item, &blk) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hashcache.rb', line 26

def read(item, &blk)

  if @h.include? item then
    !@h.expired?(item) ? self.refresh(item) : @h.delete(item)[:val]
  else
    if @file_cache == true and File.exists? @file_path + '/' + item then
      read_file item
    elsif block_given?
      self.write(item) { blk.call }
    end
  end    
end

#refresh(item) ⇒ Object



54
55
56
57
58
59
# File 'lib/hashcache.rb', line 54

def refresh(item)
  x = @h[item]    
  @h.delete item
  @h[item] = x
  x[:val]
end

#resetObject



61
62
63
# File 'lib/hashcache.rb', line 61

def reset
  @h.clear
end

#write(item, duration = nil, &blk) ⇒ Object Also known as: read!



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/hashcache.rb', line 39

def write(item, duration=nil, &blk)
  
  expiry_time = nil
  val = blk.call    
      
  expiry_time =  Time.now + ChronicDuration.parse(duration) if duration
  
  @h[item] = {val: val, expiry: duration, expiry_time: expiry_time}
  @h.shift if @h.length > @size
  write_file(item, val) if @file_cache == true
  val
end