Class: Captcher::Captchas::CachedCaptcha

Inherits:
BaseCaptcha show all
Defined in:
lib/captcher/captchas/cached_captcha.rb

Constant Summary collapse

KEY_PREFIX =
"captcher__cached__".freeze
CACHE_TTL =
1.hour

Constants inherited from BaseCaptcha

BaseCaptcha::SESSION_KEY

Instance Attribute Summary

Attributes inherited from BaseCaptcha

#config, #payload

Instance Method Summary collapse

Methods inherited from BaseCaptcha

#initialize, #own_config, restore, restore_or_create, #store

Constructor Details

This class inherits a constructor from Captcher::BaseCaptcha

Instance Method Details

#after_initializeObject



9
10
11
12
13
14
15
16
17
18
# File 'lib/captcher/captchas/cached_captcha.rb', line 9

def after_initialize
  @payload ||= Rails.cache.read(payload_key)
  if @payload
    @wrapped = wrapped_class.new(config: @config, payload: @payload)
  else
    @wrapped = wrapped_class.new(config: @config)
    @payload = @wrapped.payload
    Rails.cache.write(payload_key, @payload, expires_in: CACHE_TTL)
  end
end

#represent(format = :html, options = {}) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



21
22
23
24
25
26
27
# File 'lib/captcher/captchas/cached_captcha.rb', line 21

def represent(format = :html, options = {})
  cache_options = { expires_in: CACHE_TTL, race_condition_ttl: 10 }
  representation = Rails.cache.fetch(representation_key, cache_options) do
    Base64.encode64(@wrapped.represent)
  end
  Base64.decode64(representation)
end

#validate(confirmation) ⇒ Object

rubocop:enable Lint/UnusedMethodArgument



30
31
32
# File 'lib/captcher/captchas/cached_captcha.rb', line 30

def validate(confirmation)
  @wrapped.validate(confirmation)
end