将代码从PHP转换为Ruby on Rails

将代码从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];

我正在尝试将geoip的web服务用于rails应用程序上的ruby。 他们不提供任何ruby演示,但这是他们为PHP提供的。 我想知道是否有人知道如何将其转换为在轨道上的红宝石上工作? 我只需要数据中的城市和地区。 更多示例可以在他们的网站上找到 p>

  $ 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)
ot die('无法打开与服务器的连接。')  ; 
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); 
}其他{
#在此处输入错误处理代码
} 
 
echo $ data; 
 $ geo = explode(“,”,$ data); 
 $ country  = $ geo [0]; 
 $ state = $ geo [1]; 
 $ city = $ geo [2]; 
 $ lat = $ geo [3]; 
 $ lon = $ geo [4]  ; 
  code>  pre> 
  div>

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]