Class: GeoIP2::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/geoip2/database.rb,
ext/geoip2/geoip2.c

Instance Method Summary collapse

Constructor Details

#initialize(path, symbolize_keys: false) ⇒ Database

Returns a new instance of Database.



3
4
5
6
# File 'lib/geoip2/database.rb', line 3

def initialize(path, symbolize_keys: false)
  @symbolize_keys = !!symbolize_keys
  open_mmdb(path)
end

Instance Method Details

#closeObject



323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'ext/geoip2/geoip2.c', line 323

static VALUE
rb_geoip2_db_close(VALUE self)
{
  MMDB_s *mmdb;

  TypedData_Get_Struct(self, struct MMDB_s, &rb_mmdb_type, mmdb);

  if (!mmdb_is_closed(mmdb)) {
    mmdb_close(mmdb);
  }

  return Qnil;
}

#lookup(ip) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'ext/geoip2/geoip2.c', line 337

static VALUE
rb_geoip2_db_lookup(VALUE self, VALUE ip)
{
  char *ip_str;
  MMDB_s *mmdb;
  MMDB_lookup_result_s result;
  LookupResult *result_ptr;
  VALUE obj;

  Check_Type(ip, T_STRING);
  ip_str = StringValueCStr(ip);

  TypedData_Get_Struct(self, struct MMDB_s, &rb_mmdb_type, mmdb);
  result = mmdb_lookup(mmdb, ip_str, false);

  if (!result.found_entry) {
    return Qnil;
  }

  obj = TypedData_Make_Struct(rb_cGeoIP2LookupResult,
                              LookupResult,
                              &rb_lookup_result_type,
                              result_ptr);
  result_ptr->result = result;
  result_ptr->db = self;

  rb_iv_set(obj, "@symbolize_keys", rb_iv_get(self, "@symbolize_keys"));

  return obj;
}

#open_mmdb(path) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'ext/geoip2/geoip2.c', line 299

static VALUE
rb_geoip2_db_open_mmdb(VALUE self, VALUE path)
{
  char *db_path;
  MMDB_s *mmdb;

  Check_Type(path, T_STRING);

  db_path = StringValueCStr(path);

  TypedData_Get_Struct(self, struct MMDB_s, &rb_mmdb_type, mmdb);

  /* Reopening over an already-open database would overwrite the MMDB_s in
   * place and leak libmaxminddb's internal allocations (and the previous
   * mmap). Close the current database first. */
  if (!mmdb_is_closed(mmdb)) {
    mmdb_close(mmdb);
  }

  mmdb_open(db_path, mmdb);

  return Qnil;
}