Class: Bitsa::ContactsCache

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/bitsa/contacts_cache.rb

Overview

Cache of Contacts.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache_file_path, lifespan_days) ⇒ ContactsCache

Load cache from file system. After lifespan_days the cache is considered stale.



38
39
40
41
42
43
44
# File 'lib/bitsa/contacts_cache.rb', line 38

def initialize(cache_file_path, lifespan_days)
  @cache_file_path = File.expand_path(cache_file_path || "~/.bitsa_cache.yml")
  @lifespan_days = lifespan_days
  @addresses = {}
  @source_source_last_modified = nil
  load_from_file_system
end

Instance Attribute Details

#source_last_modifiedObject

Date/Time cache was last updated.



35
36
37
# File 'lib/bitsa/contacts_cache.rb', line 35

def source_last_modified
  @source_last_modified
end

Instance Method Details

#clear!Object

Remove all entries from cache.



52
53
54
55
# File 'lib/bitsa/contacts_cache.rb', line 52

def clear!
  @addresses.clear
  @source_last_modified = nil
end

#delete(id) ⇒ Object



78
79
80
# File 'lib/bitsa/contacts_cache.rb', line 78

def delete(id)
  @addresses.delete(id)
end

#get(id) ⇒ Object



57
58
59
# File 'lib/bitsa/contacts_cache.rb', line 57

def get(id)
  @addresses[id]
end

#saveObject



82
83
84
85
86
# File 'lib/bitsa/contacts_cache.rb', line 82

def save
  File.open(@cache_file_path, "w") do |f|
    f.write(YAML::dump([@source_last_modified, @addresses]))
  end
end

#search(qry) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/bitsa/contacts_cache.rb', line 61

def search(qry)
  qry ||= ""
  rg = Regexp.new(qry, Regexp::IGNORECASE)

  # Flattens.each_slices to an array with [email1, name1, email2, name2] etc.
  results = @addresses.values.flatten.each_slice(2).find_all do |e, n|
    e.match(rg) || n.match(rg)
  end

  # Sort by case-insensitive email address
  results.sort{|a,b| a[0].downcase <=> b[0].downcase}
end

#stale?Boolean

Returns:

  • (Boolean)


46
47
48
49
# File 'lib/bitsa/contacts_cache.rb', line 46

def stale?
  (@source_last_modified.nil? ||
   (DateTime.parse(@source_last_modified)+@lifespan_days) < DateTime.now)
end

#update(id, name, addresses) ⇒ Object



74
75
76
# File 'lib/bitsa/contacts_cache.rb', line 74

def update(id, name, addresses)
  @addresses[id] = addresses.map { | a | [a, name]}
end