class ActiveModel::Validations::IpaddrValidator
Public Class Methods
new(options)
click to toggle source
Calls superclass method
# 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
Public Instance Methods
validate_each(record, attribute, value)
click to toggle source
# 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
Private Instance Methods
ip_within_block?(ip, blk)
click to toggle source
# File lib/can_has_validations/validators/ipaddr_validator.rb, line 50 def ip_within_block?(ip, blk) return false unless ip.family == blk.family ip = ip.to_range blk = blk.to_range ip.begin >= blk.begin && ip.end <= blk.end end
normalize_within(val, key)
click to toggle source
# File lib/can_has_validations/validators/ipaddr_validator.rb, line 57 def normalize_within(val, key) if val.nil? || val.respond_to?(:call) || val.is_a?(Symbol) val else Array(val).flatten.map do |i| case i when IPAddr i when String IPAddr.new i else raise "Unexpected value for #{key.inspect} : #{i}" end end end end
resolve_array(record, val)
click to toggle source
# File lib/can_has_validations/validators/ipaddr_validator.rb, line 74 def resolve_array(record, val) res = if val.respond_to?(:call) val.call(record) elsif val.is_a?(Symbol) record.send(val) else val end # raise "#{val.inspect} did not resolve to an Array of IPAddr" unless res.is_a?(Array) && res.all?{|r| r.is_a?(IPAddr)} # res end