class Captcher::Captchas::CachedCaptcha

Constants

CACHE_TTL
KEY_PREFIX

Public Instance Methods

after_initialize() click to toggle source
# 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 = {}) click to toggle source

rubocop:disable Lint/UnusedMethodArgument

# 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) click to toggle source

rubocop:enable Lint/UnusedMethodArgument

# File lib/captcher/captchas/cached_captcha.rb, line 30
def validate(confirmation)
  @wrapped.validate(confirmation)
end

Private Instance Methods

payload_key() click to toggle source
# File lib/captcher/captchas/cached_captcha.rb, line 45
def payload_key
  "#{KEY_PREFIX}:#{own_config[:wrapped]}:#{random_slot}"
end
random_slot() click to toggle source
# File lib/captcher/captchas/cached_captcha.rb, line 49
def random_slot
  rand(own_config[:slots_count])
end
representation_key() click to toggle source
# File lib/captcher/captchas/cached_captcha.rb, line 40
def representation_key
  payload_hash = Digest::MD5.hexdigest(@payload)
  "#{KEY_PREFIX}:#{payload_hash}"
end
wrapped_class() click to toggle source
# File lib/captcher/captchas/cached_captcha.rb, line 36
def wrapped_class
  Captcher.select_captcha_class(own_config[:wrapped])
end