module JamRuby class MaxMindGeo < ActiveRecord::Base self.table_name = 'max_mind_geo' def self.ip_lookup(ip_addy) self.where(["ip_start <= ? AND ip_end >= ?", ip_addy, ip_addy]) .limit(1) .first end 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 } Band.find_each { |bnd| bnd.update_lat_lng } end def self.where_latlng(relation, params, current_user=nil) if 0 < (distance = params[:distance].to_i) latlng = [] if location_city = params[:city] if geo = self.where(:city => params[:city]).limit(1).first latlng = [geo.lat, geo.lng] end elsif current_user if current_user.lat.nil? || current_user.lng.nil? if params[:remote_ip] && (geo = self.ip_lookup(params[:remote_ip])) latlng = [geo.lat, geo.lng] if geo.lat && geo.lng end else latlng = [current_user.lat, current_user.lng] end elsif params[:remote_ip] && (geo = self.ip_lookup(params[:remote_ip])) latlng = [geo.lat, geo.lng] if geo.lat && geo.lng end if latlng.present? relation = relation.where(['lat IS NOT NULL AND lng IS NOT NULL']) .within(distance, :origin => latlng) end end relation end end end