Class: Rack::ParamToCookie

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/param_to_cookie.rb,
lib/rack/param_to_cookie/version.rb

Overview

Rack middleware. See README.

Constant Summary collapse

VERSION_MAJOR =
3
VERSION_MINOR =
1
VERSION_PATCH =
0
VERSION =
[VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH].join('.')

Instance Method Summary collapse

Constructor Details

#initialize(app, param_cookies) ⇒ ParamToCookie

Returns a new instance of ParamToCookie.

Parameters:

  • app (Object)
  • param_cookies (Hash<String, Hash>)

    map from parameter names to cookie options



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rack/param_to_cookie.rb', line 14

def initialize app, param_cookies
  @app = app
  @param_cookies = param_cookies
  @param_cookies.each do |param, options|
    options[:cookie_name] ||= param
    options[:env_name] ||= param
    options[:ttl] ||= 60*60*24*30 # 30 days
    options[:set_cookie_options] ||= {}
    options[:max_length] ||= 64 # characters
  end
end

Instance Method Details

#call(env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/rack/param_to_cookie.rb', line 26

def call env
  req = Rack::Request.new(env)

  updated_cookies = {}
  @param_cookies.each do |param, options|
    # get the value from a previously set cookie
    cookie_value = req.cookies[options[:cookie_name]]

    # check whether there's a new value for the cookie with this request
    params_value = req.params[param] rescue nil

    # validate the length of the value
    params_value = nil if
      params_value && params_value.length > options[:max_length]

    value = params_value || cookie_value
    env[options[:env_name]] = value if value

    # once we handle the response, set the new cookie value
    if params_value
      updated_cookies[options[:cookie_name]] =
        options[:set_cookie_options].merge(
          value: params_value,
          expires: Time.now + options[:ttl])
    end
  end

  status, headers, body = @app.call(env)
  response = Rack::Response.new body, status, headers

  updated_cookies.each do |cookie, options|
    response.set_cookie cookie, options
  end

  response.finish
end