Class: IpValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/ip_validator.rb

Constant Summary collapse

EXCEPTIONS =
[ ArgumentError ]

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'app/validators/ip_validator.rb', line 13

def validate_each(record, attribute, value)
  ip = IPAddr.new(value)
  rng = ip.to_range
  result = true

  result &=  ip.ipv4?               if options[:ip4_only] == true
  result &=  ip.ipv6?               if options[:ip6_only] == true

  result &=  rng.first != rng.last if options[:ranges_only] == true
  result &=  rng.first == rng.last if options[:addresses_only] == true

  result &=  IPAddr.new(options[:within]).include? ip if options[:within]

  add_error(record, attribute, value) unless result

rescue *EXCEPTIONS
  add_error(record, attribute, value)
end