Class: Kokki::IPAddress

Inherits:
Object
  • Object
show all
Defined in:
lib/kokki/ip_address.rb

Constant Summary collapse

PRIVATE_IPS =
%w(10.0.0.0/8 172.16.0.0/12 192.168.0.0/16).map { |ip| IPAddr.new(ip) }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(address) ⇒ IPAddress

Returns a new instance of IPAddress.

Raises:



11
12
13
14
15
# File 'lib/kokki/ip_address.rb', line 11

def initialize(address)
  @address = address

  raise InvalidInputError, "Invalid input: #{address}" if !valid_format? || internal?
end

Instance Attribute Details

#addressObject (readonly)

Returns the value of attribute address.



7
8
9
# File 'lib/kokki/ip_address.rb', line 7

def address
  @address
end

Instance Method Details

#country_codeObject



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/kokki/ip_address.rb', line 17

def country_code
  @country_code ||=
    [].tap do |out|
      begin
        res = IPInfo.geo(address)
        out << res.dig("country")
      rescue Error => _e
        out << nil
      end
    end.first
end

#internal?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/kokki/ip_address.rb', line 29

def internal?
  loopback? || private?
end

#loopback?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/kokki/ip_address.rb', line 33

def loopback?
  address == "0.0.0.0" || address.start_with?("127") || address == "::1"
end

#private?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/kokki/ip_address.rb', line 37

def private?
  PRIVATE_IPS.any? { |ip| ip.include?(address) }
end