require 'ipaddr'

module ThreeScale

  class IpAddressValidator < ActiveModel::EachValidator

    def validate_each(record, attribute, value)
      uri = Addressable::URI.parse(value)
      return unless uri

      ip = IPAddr.new(uri.host)

      if uri.host == ip.to_s
        record.errors.add(attribute, :ip_address)
      end

    rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError
      # the value is not an IP address
    end
  end
end