drqyxkzbs21968684 2010-01-24 22:44
浏览 47
已采纳

将代码从PHP转换为Ruby on Rails

I'm trying to use geoip's web service for a ruby on rails application. They don't give any ruby demos but this is what they give for PHP. I was wondering if anyone knew how to convert this to work on ruby on rails? I only need the city and the region from the data. More examples can be found at their site at

$query = "http://geoip3.maxmind.com/b?l=" . $license_key . "&i=" . $ipaddress;
$url = parse_url($query);
$host = $url["host"];
$path = $url["path"] . "?" . $url["query"];
$timeout = 1;
$fp = fsockopen ($host, 80, $errno, $errstr, $timeout)
or die('Can not open connection to server.');
if ($fp) {
  fputs ($fp, "GET $path HTTP/1.0
Host: " . $host . "

");
  while (!feof($fp)) {
    $buf .= fgets($fp, 128);
  }
  $lines = split("
", $buf);
  $data = $lines[count($lines)-1];
  fclose($fp);
} else {
  # enter error handing code here
}

echo $data;
$geo = explode(",",$data);
$country = $geo[0];
$state = $geo[1];
$city = $geo[2];
$lat = $geo[3];
$lon = $geo[4];
  • 写回答

1条回答 默认 最新

  • dsgd4654674 2010-01-24 22:53
    关注

    I don't have a geoip license key so cannot test it fully, but this should work:

    require 'net/http'
    
    url = 'http://geoip3.maxmind.com/b?l=%s&i=%s' % [license_key, ip_address]
    res = Net::HTTP.get_response(URI.parse(url))
    
    lines = res.body.split("
    ")
    
    geo = lines[-1].split(',')
    
    country = geo[0]
    state = geo[1]
    city = geo[2]
    lat = geo[3]
    lon = geo[4]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP