Class: IpCountry

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/ip_country.rb

Constant Summary collapse

@@cache =
{}

Class Method Summary collapse

Class Method Details

.country_from_ip(ip) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/models/ip_country.rb', line 5

def self.country_from_ip(ip)
  if cached = @@cache[ip]
    return cached
  end

  if @@cache.size > 1000
    i = 100
    @@cache.each do |k,v| 
      @@cache.delete(k)
      i += 1
      break if i > 100
    end
  end

  lookup = IpCountry.select("name, risk, inet_aton('#{ip}') as ipd, ip_from, country_code").where("ip_to >= inet_aton('#{ip}')").first
  if lookup
    if lookup.ipd <= lookup.ip_from
      lookup = IpCountry.new(:risk=>50, :name=>"Unknown") 
    else
      @@cache[ip] = lookup
    end
  end

  return lookup
end