Sha256: c298189ad4b63ce80ef9bd5a101372b0418548b208ba6646f11b465865acb607

Contents?: true

Size: 745 Bytes

Versions: 2

Compression:

Stored size: 745 Bytes

Contents

require 'resolv'
module Geocoder
  class IpAddress < String
    PRIVATE_IPS = [
      '10.0.0.0/8',
      '172.16.0.0/12',
      '192.168.0.0/16',
    ].map { |ip| IPAddr.new(ip) }.freeze

    def initialize(ip)
      ip = ip.to_string if ip.is_a?(IPAddr)
      if ip.is_a?(Hash)
        super(**ip)
      else
        super(ip)
      end
    end

    def internal?
      loopback? || private?
    end

    def loopback?
      valid? and !!(self == "0.0.0.0" or self.match(/\A127\./) or self == "::1")
    end

    def private?
      valid? && PRIVATE_IPS.any? { |ip| ip.include?(self) }
    end

    def valid?
      ip = self[/(?<=\[)(.*?)(?=\])/] || self
      !!((ip =~ Resolv::IPv4::Regex) || (ip =~ Resolv::IPv6::Regex))
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
geocoder-1.8.3 lib/geocoder/ip_address.rb
geocoder-1.8.2 lib/geocoder/ip_address.rb