Class: ActiveModel::Validations::IpaddrValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/can_has_validations/validators/ipaddr_validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ IpaddrValidator

Returns a new instance of IpaddrValidator.



16
17
18
19
20
# File 'lib/can_has_validations/validators/ipaddr_validator.rb', line 16

def initialize(options)
  options[:within]  = normalize_within options[:within], :within
  options[:without] = normalize_within options[:without], :without
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/can_has_validations/validators/ipaddr_validator.rb', line 22

def validate_each(record, attribute, value)
  allowed_ips    = resolve_array record, options[:within]
  disallowed_ips = resolve_array record, options[:without]

  ip = case value
    when IPAddr
      ip
    when String
      IPAddr.new(value) rescue nil
  end
  unless ip
    record.errors.add(attribute, :invalid_ip, **options.merge(value: value))
    return
  end

  if !options[:allow_block] && (ip.ipv4? && ip.prefix!=32 or ip.ipv6? && ip.prefix!=128)
    record.errors.add(attribute, :single_ip_required, **options.merge(value: value))
  end
  if allowed_ips && allowed_ips.none?{|blk| ip_within_block? ip, blk}
    record.errors.add(attribute, :ip_not_allowed, **options.merge(value: value))
  elsif disallowed_ips && disallowed_ips.any?{|blk| ip_within_block? ip, blk}
    record.errors.add(attribute, :ip_not_allowed, **options.merge(value: value))
  end
end