Class: Shugoi::GuardCache

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

Constant Summary collapse

TTL_MS =
300_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_client) ⇒ GuardCache

Returns a new instance of GuardCache.



8
9
10
11
12
13
# File 'lib/shugoi/guard_cache.rb', line 8

def initialize(api_client)
  @api_client = api_client
  @detect = nil
  @fetched_at = 0
  @mutex = Mutex.new
end

Instance Attribute Details

#detectObject (readonly)

Returns the value of attribute detect.



6
7
8
# File 'lib/shugoi/guard_cache.rb', line 6

def detect
  @detect
end

Instance Method Details

#ensure_ready(site_key, secret = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/shugoi/guard_cache.rb', line 15

def ensure_ready(site_key, secret = nil)
  return if @detect && Utils.now_ms - @fetched_at < TTL_MS

  @mutex.synchronize do
    return if @detect && Utils.now_ms - @fetched_at < TTL_MS
    code = @api_client.fetch_guard_detect(site_key, secret)
    @detect = code && !code.empty? ? code : 'console.error("Shugoi guard-detect unavailable")'
    @fetched_at = Utils.now_ms
  end
end