Sha256: 7017708c87eaa21816067f7cad566a70e76c71007cbfc2fc9b3ead9627f95e79

Contents?: true

Size: 1.23 KB

Versions: 2

Compression:

Stored size: 1.23 KB

Contents

module CacheableFlash
  class Middleware
    require 'cacheable_flash/cookie_flash'
    include CacheableFlash::CookieFlash
    FLASH_HASH_KEY = "action_dispatch.request.flash_hash".freeze

    def initialize(app)
      @app = app
    end

    # Cookies stick in the flash until rendered (cleared out of the cookie by javascript),
    #   to ensure they are seen and not lost, so we grab them from the rails flash hash, or the request cookies
    def call(env)
      status, headers, body = @app.call(env)
      env_flash = env[FLASH_HASH_KEY]

      if env_flash
        response = Rack::Response.new(body, status, headers)
        cookies = env["rack.cookies"] || {}
        response.set_cookie("flash", { :value => cookie_flash(env_flash, cookies), :path => "/" })
        response.finish
      else
        request = ActionDispatch::Request.new(env)
        cflash = request.respond_to?(:cookie_jar) ?
          request.cookie_jar['flash'] :
          nil
        if cflash
          response = Rack::Response.new(body, status, headers)
          response.set_cookie("flash", { :value => cflash, :path => "/" })
          response.finish
        else
          response = body
        end
      end
      [status, headers, response]
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cacheable_flash-0.3.1 lib/cacheable_flash/middleware.rb
cacheable_flash-0.3.0 lib/cacheable_flash/middleware.rb