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.



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

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.



54
55
56
57
# File 'lib/bitsa/contacts_cache.rb', line 54

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

#delete(id) ⇒ Object



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

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

#get(id) ⇒ Object



59
60
61
# File 'lib/bitsa/contacts_cache.rb', line 59

def get(id)
  @addresses[id]
end

#saveObject



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

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

#search(qry) ⇒ Object



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

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

  # Flatten 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)


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

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

#update(id, name, addresses) ⇒ Object



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

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