Class: Mobvious::Strategies::Cookie
- Inherits:
-
Object
- Object
- Mobvious::Strategies::Cookie
- 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
-
#get_device_type(request) ⇒ Symbol
Gets device type using a pre-set cookie.
-
#initialize(allowed_device_types, cookie_expires = (365*24*60*60)) ⇒ Cookie
constructor
Creates a new Cookie strategy instance.
-
#response_callback(request, response) ⇒ Object
Automatically sets the device type cookie again to prolong its expiration date.
-
#set_device_type(response, device_type) ⇒ Object
Sets the device type cookie.
Constructor Details
#initialize(allowed_device_types, cookie_expires = (365*24*60*60)) ⇒ Cookie
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, = (365*24*60*60)) @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
#get_device_type(request) ⇒ Symbol
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) = request.['mobvious.device_type'] .to_sym if @allowed_device_types.include? end |
#response_callback(request, response) ⇒ Object
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.headers["Set-Cookie"] && !!response.headers["Set-Cookie"]["mobvious.device_type"] = request.['mobvious.device_type'] # re-set the cookie to renew the expiration date if && ! set_device_type(response, ) end end end |
#set_device_type(response, device_type) ⇒ Object
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.('mobvious.device_type', { value: device_type.to_s, path: '/', expires: Time.now + @cookie_expires }) end |