1module GeoipLookup |
|
2 extend ActiveSupport::Concern |
|
4 module ClassMethods |
|
5 def geoip_lookup(ip) |
|
6 geoip_db.lookup(ip)
|
|
7 rescue Errno::ENOENT => e |
|
8 nil |
|
9 end |
|
11 def iso_code_for(ip) |
|
|
12 if result = geoip_lookup(ip) |
13 result.found? ? result.country.iso_code : nil |
|
14 end |
|
15 end |
|
17 def country_name_for(ip) |
|
|
18 if result = geoip_lookup(ip) |
19 result.found? ? result.country.name : nil |
|
20 end |
|
21 end |
|
23 private
|
|
25 def geoip_db |
|
26 Thread.current[:__geoip_db__] ||= MaxMindDB.new(ENV.fetch('GEOIP_DB_PATH')) |
|
27 end |
|
28 end |
|
|
30 def geoip_lookup(ip) |
31 self.class.geoip_lookup(ip) |
|
32 end |
|
|
34 def iso_code_for(ip) |
35 self.class.iso_code_for(ip) |
|
36 end |
|
|
38 def country_name_for(ip) |
39 self.class.country_name_for(ip) |
|
40 end |
|
|
42 def ip_location |
43 return unless ip_address? |
|
|
45 if iso_code = iso_code_for(ip_address) |
46 "#{ip_address} (#{iso_code})" |
|
47 else |
|
48 ip_address
|
|
49 end |
|
50 end |
|
51end |