geo_location

2444 ワード

ユーザのIPでその位置を判断する.あなたはhostipを選ぶことができます。info(無料)またはmaxmind.com(有料)、中間処理とします。 country.rb(2つの方法) module GeoLocation class << self def country(country_code) return nil if GeoLocation::countries.empty? GeoLocation::countries[country_code.to_sym] end def build_countries if GeoLocation::countries.empty? data = {} file = File.join(File.dirname(__FILE__), 'countries.txt') File.open(file, "r") do |infile| while (line = infile.gets) countries = line.split("") countries.each do |c| c = c.split(" ") code = c[0].to_sym country = c[1] data[code] = country end # end countries.each end # end while end # end file.open GeoLocation::countries = data end # end if end end end timezone.rb(2つの方法) module GeoLocation class << self def timezone(country, region=nil) return nil if GeoLocation::timezones.empty? (region.nil? || region.empty?) ? GeoLocation::timezones[country.to_sym] : GeoLocation::timezones[country.to_sym][region.to_sym] end def build_timezones if GeoLocation::timezones.empty? data = {} file = File.join(File.dirname(__FILE__), 'timezones.txt') File.open(file, "r") do |infile| while (line = infile.gets) zones = line.split("") zones.each do |z| zone = z.split(" ") country = zone[0].to_sym region = zone[1].empty? ? '' : zone[1].to_sym value = zone[2] data[country] = {} if data[country].nil? if region.to_s.empty? data[country] = value else data[country][region] = value end end # end zones.each end # end while end # end file.open GeoLocation::timezones = data end # end if end end end find(ip=nil)で検索 ソース: def find(ip=nil) ip = GeoLocation::dev_ip unless GeoLocation::dev_ip.nil? return nil unless valid_ip(ip) return (GeoLocation::use == :maxmind) ? maxmind(ip) : hostip(ip) end 例を挙げる location = GeoLocation.find('24.24.24.24') # => {:ip=>"24.24.24.24", :city=>"Liverpool", :region=>"NY", :country=>"United States", :country_code=>"US", :latitude=>"43.1059", :longitude=>"-76.2099", :timezone=>"America/New_York"} puts location[:ip] # => 24.24.24.24 puts location[:city] # => Liverpool puts location[:region] # => NY puts location[:country] # => United States puts location[:country_code] # => US puts location[:latitude] # => 43.1059 puts location[:longitude] # => -76.2099 puts location[:timezone] # => America/New_York