Class: Mack::CookieJar

Inherits:
Object show all
Defined in:
lib/mack/controller/cookie_jar.rb

Overview

Examples:

class MyAwesomeController
  include Mack::Controller
  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:



21
22
23
24
25
# File 'lib/mack/controller/cookie_jar.rb', line 21

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

Instance Attribute Details

#all_cookiesObject (readonly)

:nodoc:



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

def all_cookies
  @all_cookies
end

#requestObject (readonly)

:nodoc:



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

def request
  @request
end

#responseObject (readonly)

:nodoc:



19
20
21
# File 'lib/mack/controller/cookie_jar.rb', line 19

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.



30
31
32
33
34
35
36
37
38
# File 'lib/mack/controller/cookie_jar.rb', line 30

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.



41
42
43
44
45
46
47
48
49
# File 'lib/mack/controller/cookie_jar.rb', line 41

def []=(key, value)
  key = key.to_s
  unless value.is_a?(Hash)
    value = {:value => value}
  end
  value = configatron.mack.cookie_values.to_hash.symbolize_keys.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.



62
63
64
# File 'lib/mack/controller/cookie_jar.rb', line 62

def all
  self.all_cookies
end

#delete(key) ⇒ Object

Deletes a cookie.



52
53
54
55
56
# File 'lib/mack/controller/cookie_jar.rb', line 52

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

#inspectObject



66
67
68
# File 'lib/mack/controller/cookie_jar.rb', line 66

def inspect
  self.all_cookies.inspect
end