Sha256: 305cc91087f06e7179790a328f59c983c335da01dece3e43bf061c1c035c8fa5

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

module Captcher
  module Captchas
    class CachedCaptcha < BaseCaptcha
      KEY_PREFIX = "captcher__cached__".freeze
      CACHE_TTL = 1.hour

      self.name = :cached_captcha

      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

      # rubocop:disable Lint/UnusedMethodArgument
      def represent(format = :html, options = {})
        Rails.cache.fetch(representation_key, expires_in: CACHE_TTL) do
          @wrapped.represent
        end
      end
      # rubocop:enable Lint/UnusedMethodArgument

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

      private

      def wrapped_class
        Captcher.select_captcha_class(own_config[:wrapped])
      end

      def representation_key
        payload_hash = Digest::MD5.hexdigest(@payload)
        "#{KEY_PREFIX}:#{payload_hash}"
      end

      def payload_key
        "#{KEY_PREFIX}:#{own_config[:wrapped]}:#{random_slot}"
      end

      def random_slot
        rand(own_config[:slots_count])
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
captcher-0.2.0 lib/captcher/captchas/cached_captcha.rb