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
|
# File 'lib/can_has_validations/validators/url_validator.rb', line 16
def validate_each(record, attribute, value)
if defined?(Addressable::URI)
u = Addressable::URI.parse(value) rescue nil
u2 = u && URI.parse(u.normalize.to_s) rescue nil
else
u2 = u = URI.parse(value) rescue nil
end
allowed_schemes =
if options[:scheme].respond_to?(:call)
options[:scheme].call(record)
elsif options[:scheme].is_a?(Symbol)
record.send(options[:scheme])
else
Array.wrap(options[:scheme] || %w(http https))
end
allowed_hosts =
if options[:host].respond_to?(:call)
options[:host].call(record)
elsif options[:host].is_a?(Symbol)
record.send(options[:host])
elsif options[:host].nil?
[u&.host]
else
Array.wrap(options[:host])
end
allowed_ports =
if options[:port].respond_to?(:call)
options[:port].call(record)
elsif options[:port].is_a?(Symbol)
record.send(options[:port])
elsif options[:port].nil?
[u&.port]
elsif options[:port] == false
[nil]
else
Array.wrap(options[:port])
end
if !u || !u2 || u.relative? || allowed_schemes.exclude?(u.scheme) || allowed_hosts.exclude?(u.host) || allowed_ports.exclude?(u.port)
record.errors.add(attribute, :invalid_url, **options.merge(value: value, scheme: allowed_schemes, host: allowed_hosts, port: allowed_ports))
end
end
|