Class: Mobvious::Strategies::Cookie

Inherits:
Object
  • Object
show all
Defined in:
lib/mobvious/strategies/cookie.rb

Overview

Mobvious device detection strategy that saves and loads a cookie that precisely specifies which device type should be used for current client.

Usually, you will want to set the device type via cookie only when you are absolutely sure that user wants it this way (e.g. after manual switch between mobile/desktop interface versions performed by user). Also make sure to use this strategy with high priority, (e.g. put it before user-agent based detection) so it does not get overriden.

Use #set_device_type method to set the device type and the strategy will then recognize it on subsequent requests.

Instance Method Summary (collapse)

Constructor Details

- (Cookie) initialize(allowed_device_types, cookie_expires = (365*24*60*60))

Creates a new Cookie strategy instance.



21
22
23
24
25
26
27
# File 'lib/mobvious/strategies/cookie.rb', line 21

def initialize(allowed_device_types, cookie_expires = (365*24*60*60))
  @cookie_expires = cookie_expires

  # device types must be compared with the cookie as strings to prevent attacks
  # against .to_sym that could lead to memory leaks
  @allowed_device_types = allowed_device_types.map {|device_type| device_type.to_s }
end

Instance Method Details

- (Symbol) get_device_type(request)

Gets device type using a pre-set cookie. Returns nil if the cookie is not set or its value is not listed among allowed_device_types (the list can be defined in #initialize).



34
35
36
37
# File 'lib/mobvious/strategies/cookie.rb', line 34

def get_device_type(request)
  cookie_value = request.cookies['mobvious.device_type']
  cookie_value.to_sym if @allowed_device_types.include? cookie_value
end

- (Object) response_callback(request, response)

Automatically sets the device type cookie again to prolong its expiration date.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mobvious/strategies/cookie.rb', line 43

def response_callback(request, response)
  if response.respond_to? :headers

    response_cookie_already_set = !!response.headers["Set-Cookie"] &&
      !!response.headers["Set-Cookie"]["mobvious.device_type"]
    request_cookie = request.cookies['mobvious.device_type']

    # re-set the cookie to renew the expiration date
    if request_cookie && !response_cookie_already_set
      set_device_type(response, request_cookie)
    end

  end
end

- (Object) set_device_type(response, device_type)

Sets the device type cookie.



62
63
64
65
# File 'lib/mobvious/strategies/cookie.rb', line 62

def set_device_type(response, device_type)
  response.set_cookie('mobvious.device_type',
                      { value: device_type.to_s, path: '/', expires: Time.now + @cookie_expires })
end