Module: Fastr::Cookie

Included in:
Controller
Defined in:
lib/fastr/cookie.rb

Overview

This module adds helpers for handling cookies.

Setting a cookie

set_cookie("mycookie", "value", {:expires => Time.now + 3600})

Author:

  • Chris Moos

Instance Method Summary collapse

Instance Method Details

Adds a Set-Cookie header in the response.

Parameters:

  • key (String)
  • value (String)
  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :expires (Time)

    The time when the cookie should expire.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/fastr/cookie.rb', line 15

def set_cookie(key, value, options={})
  cookie = ["#{key}=#{value};"]


  if options.has_key? :expires and options[:expires].kind_of? Time
    options[:expires] = options[:expires].utc.strftime('%a, %d-%b-%Y %H:%M:%S GMT')
  end

  # Sort the cookies alphabetically.
  options.sort { |a,b| a.to_s <=> b.to_s }.each do |k,v|
    cookie << "#{k}=#{v.to_s};"
  end

  cookie_val = cookie.join(' ')

  if self.headers['Set-Cookie'].nil?
    self.headers['Set-Cookie'] = [cookie_val]
  else
    self.headers['Set-Cookie'] << cookie_val
  end
end