使用Ruby on Rails从原始IP地址获取用户国家/地区名称 [英] Getting a user country name from originating IP address with Ruby on Rails

查看:84
本文介绍了使用Ruby on Rails从原始IP地址获取用户国家/地区名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从访问者的IP地址中提取用户国家/地区名称.

I want to extract a user country name from visitors' IP addresses.

我可以用remote_ip来获取IP地址.但是可能是什么 最简单的获取国家名称的方法?

I could get the IP address with remote_ip. But what could be the easiest way to get the country name?

它不一定是超级准确的.任何红宝石库(gem或插件)都可以做到这一点?

It doesn't have to be super accurate. Any ruby library (gem or plugin) to do this?

我想要一个简单的解决方案.

I want an simple and easy solution for this.

推荐答案

您可以使用geoip gem.

environment.rb

environment.rb

config.gem 'geoip'

http://www.maxmind.com/app/geolitecountry下载GeoIP.dat.gz.解压缩文件.下面假设在#{RAILS_ROOT}/db目录下.

Download GeoIP.dat.gz from http://www.maxmind.com/app/geolitecountry. unzip the file. The below assumes under #{RAILS_ROOT}/db dir.

@geoip ||= GeoIP.new("#{RAILS_ROOT}/db/GeoIP.dat")    
remote_ip = request.remote_ip 
if remote_ip != "127.0.0.1" #todo: check for other local addresses or set default value
  location_location = @geoip.country(remote_ip)
  if location_location != nil     
    @model.country = location_location[2]
  end
end

这篇关于使用Ruby on Rails从原始IP地址获取用户国家/地区名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆