Class: Mack::CookieJar

Inherits:
Object
  • Object
show all
Defined in:
lib/sea_level/cookie_jar.rb

Overview

Examples:

class MyAwesomeController < Mack::Controller::Base
  def index
    cookies[:id] = 1
    render(:text => "Hello!")
  end

  def show
    render(:text => "The id in the cookie is: #{cookies[:id]}")
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request, response) ⇒ CookieJar

:nodoc:



20
21
22
23
24
# File 'lib/sea_level/cookie_jar.rb', line 20

def initialize(request, response) # :nodoc:
  @request = request
  @response = response
  @all_cookies = request.cookies
end

Instance Attribute Details

#all_cookiesObject (readonly)

:nodoc:



16
17
18
# File 'lib/sea_level/cookie_jar.rb', line 16

def all_cookies
  @all_cookies
end

#requestObject (readonly)

:nodoc:



17
18
19
# File 'lib/sea_level/cookie_jar.rb', line 17

def request
  @request
end

#responseObject (readonly)

:nodoc:



18
19
20
# File 'lib/sea_level/cookie_jar.rb', line 18

def response
  @response
end

Instance Method Details

#[](key) ⇒ Object

Returns the value of a cookie as a String, or nil it doesn’t exist. This will check both the incoming cookies on the request, as well as any cookies that have been set as part of the current action.



29
30
31
32
33
34
35
36
37
# File 'lib/sea_level/cookie_jar.rb', line 29

def [](key)
  return nil if key.nil?
  # check both the incoming cookies and the outgoing cookies to see if 
  # the cookie we're looking for exists.
  c = (self.all_cookies[key.to_s] || self.all_cookies[key.to_sym])
  return c if c.is_a?(String)
  return c[:value] if c.is_a?(Hash)
  return nil
end

#[]=(key, value) ⇒ Object

Set a cookie with a specified value.



40
41
42
43
44
45
46
47
48
# File 'lib/sea_level/cookie_jar.rb', line 40

def []=(key, value)
  key = key.to_s
  unless value.is_a?(Hash)
    value = {:value => value}
  end
  value = app_config.mack.cookie_values.merge(value)
  self.all_cookies[key] = value
  self.response.set_cookie(key, value)
end

#allObject

Returns both cookies that came in as part of the request, as well as those set on to the response. This is useful when you set a cookie in a filter or an action and want to access it in another filter or action before the request/response has been fully completed.



61
62
63
# File 'lib/sea_level/cookie_jar.rb', line 61

def all
  self.all_cookies
end

#delete(key) ⇒ Object

Deletes a cookie.



51
52
53
54
55
# File 'lib/sea_level/cookie_jar.rb', line 51

def delete(key)
  key = key.to_s
  self.all_cookies.delete(key)
  self.response.delete_cookie(key)
end