This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
url.rb
70 lines (62 loc) · 2.57 KB
/
url.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module Mobvious
module Strategies
# Mobvious device detection strategy that uses URL pattern matching.
class URL
# Rule set with only one rule for domains that begin with `m.` matching as `:mobile`.
MOBILE_PATH_RULES = { /^\w+:\/\/m\./ => :mobile }
# Creates a new URL strategy instance.
#
# @param rules
# A hash containing regular expressions mapped to symbols. The regular expression
# is evaluated against the whole URL of the request (including `http://`). If matching,
# the corresponding symbol is returned as the device type.
# **or**
# a symbol for one of predefined detection rules (`:mobile_path_rules`)
# @param options
# A hash with strategy options.
# `disable_if_referer_set: true` disables the strategy if HTTP Referer header is set
# `disable_if_referer_matches: /regex/` disables the strategy if HTTP Referer matches
# given regular expression
# `disable_unless_referer_matches: /regex/` disables the strategy if HTTP Referer
# doesn't match given regular expression
def initialize(rules = :mobile_path_rules, options = {})
if rules.is_a? Symbol
@rules = eval(rules.to_s.upcase)
else
@rules = rules
end
default_options = {
disable_if_referer_set: false,
disable_if_referer_matches: nil,
disable_unless_referer_matches: nil
}
@options = default_options.merge(options)
end
# Gets device type using URL pattern matching. Returns nil if no match found.
#
# @param request [Rack::Request]
# @return [Symbol] device type or nil
def get_device_type(request)
return nil if disabled_by_referer_set?(request) ||
disabled_by_referer_matching?(request) ||
disabled_by_referer_not_matching?(request)
@rules.each do |regex, device_type|
return device_type if request.url =~ regex
end
nil
end
private
def disabled_by_referer_set?(request)
@options[:disable_if_referer_set] && request.env['HTTP_REFERER']
end
def disabled_by_referer_matching?(request)
@options[:disable_if_referer_matches] &&
request.env['HTTP_REFERER'] =~ @options[:disable_if_referer_matches]
end
def disabled_by_referer_not_matching?(request)
@options[:disable_unless_referer_matches] &&
request.env['HTTP_REFERER'] !~ @options[:disable_unless_referer_matches]
end
end
end
end