Class: Opener::PropertyTagger::RemoteAspectsCache

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/opener/property_tagger/remote_aspects_cache.rb

Overview

Thread-safe cache for storing the contents of remote aspects.

Constant Summary collapse

UPDATE_INTERVAL =
(ENV['CACHE_EXPIRE_MINS']&.to_i || 5).minutes

Instance Method Summary collapse

Constructor Details

#initializeRemoteAspectsCache

Returns a new instance of RemoteAspectsCache.



12
13
14
15
16
17
# File 'lib/opener/property_tagger/remote_aspects_cache.rb', line 12

def initialize
  super

  @url   = ENV['PROPERTY_TAGGER_LEXICONS_URL']
  @cache = {}
end

Instance Method Details

#[](**params) ⇒ Object Also known as: get



19
20
21
22
23
24
25
# File 'lib/opener/property_tagger/remote_aspects_cache.rb', line 19

def [] **params
  synchronize do
    existing = @cache[params]
    break existing if existing and existing.from > UPDATE_INTERVAL.ago
    @cache[params] = cache_update existing, **params
  end
end

#cache_update(existing = nil, **params) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/opener/property_tagger/remote_aspects_cache.rb', line 28

def cache_update existing = nil, **params
  from     = Time.now
  lexicons = load_aspects cache: existing, **params

  if existing and lexicons.blank?
    existing.from = from
    return existing
  end

  Hashie::Mash.new(
    aspects: lexicons,
    from:    from,
  )
end

#load_aspects(lang:, cache:, **params) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/opener/property_tagger/remote_aspects_cache.rb', line 43

def load_aspects lang:, cache:, **params
  url  = "#{@url}&language_code=#{lang}&#{params.to_query}"
  url += "&if_updated_since=#{cache.from.utc.iso8601}" if cache
  puts "#{lang}: loading aspects from #{url}"

  lexicons = JSON.parse HTTPClient.new.get(url).body
  lexicons = lexicons['data'].map{ |l| Hashie::Mash.new l }
  mapping  = Hash.new{ |hash, key| hash[key] = [] }
  lexicons.each do |l|
    mapping[l.lemma.to_sym] << l.aspect
  end

  mapping
end