51 lines
1.8 KiB
Ruby
51 lines
1.8 KiB
Ruby
require 'csv'
|
|
module JamRuby
|
|
class MaxMindGeo < ActiveRecord::Base
|
|
|
|
self.table_name = 'max_mind_geo'
|
|
|
|
|
|
def self.import_from_max_mind(file)
|
|
# File Geo-139
|
|
# Format:
|
|
# startIpNum,endIpNum,country,region,city,postalCode,latitude,longitude,dmaCode,areaCode
|
|
|
|
MaxMindGeo.transaction do
|
|
cols = [:startIpNum, :endIpNum, :country, :region, :city, :latitude, :longitude]
|
|
MaxMindGeo.delete_all
|
|
File.open(file, 'r:ISO-8859-1') do |io|
|
|
MaxMindGeo.pg_copy_from(io, :map => {
|
|
'startIpNum' => 'ip_start',
|
|
'endIpNum' => 'ip_end',
|
|
'country' => 'country',
|
|
'region' => 'region',
|
|
'city' => 'city',
|
|
'latitude' => 'lat',
|
|
'longitude' => 'lng'},
|
|
:columns => cols) do |row|
|
|
row[0] = row[0]
|
|
row[1] = row[1]
|
|
row[2] = MaxMindIsp.strip_quotes(row[2])
|
|
row[3] = MaxMindIsp.strip_quotes(row[3])
|
|
row[4] = MaxMindIsp.strip_quotes(row[4])
|
|
row.delete_at(5)
|
|
row.delete_at(-1) if 8 <= row.count
|
|
row.delete_at(-1) if 8 <= row.count
|
|
end
|
|
end
|
|
end
|
|
User.find_each { |usr| usr.update_lat_lng }
|
|
end
|
|
|
|
|
|
# Make an IP address fit in a signed int. Just divide it by 2, as the least significant part
|
|
# just can't possibly matter. We can verify this if needed. My guess is the entire bottom octet is
|
|
# actually irrelevant
|
|
def self.ip_address_to_int(ip)
|
|
ip.split('.').inject(0) {|total,value| (total << 8 ) + value.to_i} / 2
|
|
end
|
|
end
|
|
|
|
|
|
end
|