Class: IpGeoLookup::MMDB

Inherits:
Object
  • Object
show all
Defined in:
lib/ip_geo_lookup/mmdb.rb

Overview

Pure Ruby reader for MaxMind's MMDB binary format.

Constant Summary collapse

MODE_MEMORY =
:memory
MODE_FILE =
:file
METADATA_MARKER =
"\xAB\xCD\xEFMaxMind.com".b.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, mode: MODE_MEMORY) ⇒ MMDB

Returns a new instance of MMDB.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ip_geo_lookup/mmdb.rb', line 13

def initialize(path, mode: MODE_MEMORY)
  raise DatabaseNotFoundError, "Database file not found: #{path}" unless File.exist?(path)

  @closed = false

  case mode
  when MODE_MEMORY
    @data = File.binread(path)
    @use_file = false
  when MODE_FILE
    @io = File.open(path, "rb")
    @file_size = @io.size
    @use_file = true
    @has_pread = @io.respond_to?(:pread)
    @file_mutex = Mutex.new unless @has_pread
  else
    raise ArgumentError, "Unknown mode: #{mode}. Use :memory or :file"
  end

  
end

Instance Attribute Details

#metadataObject (readonly)

Returns the value of attribute metadata.



11
12
13
# File 'lib/ip_geo_lookup/mmdb.rb', line 11

def 
  
end

Instance Method Details

#closeObject



50
51
52
53
54
55
56
57
58
# File 'lib/ip_geo_lookup/mmdb.rb', line 50

def close
  @closed = true
  if @use_file
    @io&.close
    @io = nil
  else
    @data = nil
  end
end

#find(ip_int, bit_count) ⇒ Object

Returns the MMDB record Hash for the given IP integer, or nil.

Raises:



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ip_geo_lookup/mmdb.rb', line 36

def find(ip_int, bit_count)
  raise ClosedError, "Reader is closed" if @closed

  if bit_count == 32 && @ip_version == 6
    start = ipv4_start_node
    return nil if start >= @node_count
    search_tree(ip_int, 32, start)
  elsif bit_count == 128 && @ip_version == 4
    nil
  else
    search_tree(ip_int, bit_count, 0)
  end
end