Class: IPCat

Inherits:
Object
  • Object
show all
Defined in:
lib/ipcat.rb,
lib/ipcat/iprange.rb,
lib/ipcat/version.rb

Defined Under Namespace

Classes: IPRange

Constant Summary collapse

VERSION =
'2.0.23'

Class Method Summary collapse

Class Method Details

.bsearch(needle, haystack = ranges, first = 0, last = ranges.size - 1) ⇒ Object

Assume ranges is an array of comparable objects



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ipcat.rb', line 54

def bsearch(needle, haystack = ranges, first = 0, last = ranges.size - 1)
  return nil if last < first # not found, or empty range

  cur = first + (last - first) / 2
  case haystack[cur] <=> needle
  when -1 # needle is larger than cur value
    bsearch(needle, haystack, cur + 1, last)
  when 1 # needle is smaller than cur value
    bsearch(needle, haystack, first, cur - 1)
  when 0
    haystack[cur]
  end
end

.datacenter?(ip) ⇒ Boolean Also known as: classify

Returns:

  • (Boolean)


13
14
15
# File 'lib/ipcat.rb', line 13

def datacenter?(ip)
  bsearch(ip_to_integer(ip))
end

.ip_to_integer(ip) ⇒ Object



18
19
20
# File 'lib/ipcat.rb', line 18

def ip_to_integer(ip)
  Integer === ip ? ip : IPAddr.new(ip).to_i
end

.load!Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ipcat.rb', line 41

def load!
  reset_ranges!
  # NB: loading an array of marshaled ruby objects takes ~15ms;
  # versus ~100ms to load a CSV file
  path = File.join(File.dirname(__FILE__), '..', 'data', 'datacenters')
  @ranges = Marshal.load(File.read(path))
  @ranges.each(&:freeze)
  @ranges.freeze
rescue
  load_csv!
end

.load_csv!(path = 'https://raw.githubusercontent.com/rale/ipcat/master/datacenters.csv') ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/ipcat.rb', line 30

def load_csv!(path = 'https://raw.githubusercontent.com/rale/ipcat/master/datacenters.csv')
  reset_ranges!

  require 'open-uri'
  open(path).readlines.each do |line|
    first, last, name, url = line.split(',')
    ranges << IPRange.new(first, last, name, url).freeze
  end
  ranges.freeze
end

.rangesObject



22
23
24
# File 'lib/ipcat.rb', line 22

def ranges
  @ranges ||= []
end

.reset_ranges!(new_ranges = []) ⇒ Object



26
27
28
# File 'lib/ipcat.rb', line 26

def reset_ranges!(new_ranges = [])
  @ranges = new_ranges
end