Sha256: eb8a708d4f95145dd90f4d9d1e25fe8b1f5c945d4082a47d061dfb48ce97939b

Contents?: true

Size: 783 Bytes

Versions: 1

Compression:

Stored size: 783 Bytes

Contents

module UniversalValidators
  class IpValidator
    def initialize(ip, mask_presence = false)
      @ip = ip.to_s
      @mask_presence = mask_presence
    end

    def valid?
      begin
        check_format_with_netmask if @mask_presence
        check_format_without_netmask unless @mask_presence
      rescue
        return
      end

      @ip.split('.').select { |pair| pair.to_i > 255 }.length == 0
    end

    private

    def check_format_without_netmask
      fail ArgumentError unless @ip.match(/\A[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\Z/)
    end

    def check_format_with_netmask
      fail ArgumentError unless @ip.match(/\A[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}\Z/)
      fail ArgumentError if @ip.split('/')[1].to_i > 32
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
universal_validators-1.0.0 lib/universal_validators/ip_validator.rb