Geocoder,当ip为127.0.0.1时如何在本地测试?

我无法让地理编码器正常工作,因为我的本地IP地址是127.0.0.1所以它无法找到我正确的位置。

request.location.ip显示“127.0.0.1”

我怎样才能使用不同的IP地址(我的互联网连接ip),这样可以带来更多相关数据?

一个很好的干净方法是使用MiddleWare。 将此类添加到lib目录:

# lib/spoof_ip.rb class SpoofIp def initialize(app, ip) @app = app @ip = ip end def call(env) env['HTTP_X_FORWARDED_FOR'] = nil env['REMOTE_ADDR'] = env['action_dispatch.remote_ip'] = @ip @status, @headers, @response = @app.call(env) [@status, @headers, @response] end end 

然后找到要用于开发环境的IP地址,并将其添加到development.rb文件中:

 config.middleware.use('SpoofIp', '64.71.24.19') 

为此,我通常使用params[:ip]或开发中的东西。 这允许我测试其他IP地址的function,并假装我在世界的任何地方。

例如

 class ApplicationController < ActionController::Base def request_ip if Rails.env.development? && params[:ip] params[:ip] else request.remote_ip end end end 

我实现了这个略有不同,这适用于我的情况。

application_controller.rb我有一个查询方法,它直接调用geocoder IP查找传递request.remote_ip的结果。

 def lookup_ip_location if Rails.env.development? Geocoder.search(request.remote_ip).first else request.location end end 

然后在config/environments/development.rb我修补了remote_ip调用:

 class ActionDispatch::Request def remote_ip "71.212.123.5" # ipd home (Denver,CO or Renton,WA) # "208.87.35.103" # websiteuk.com -- Nassau, Bahamas # "50.78.167.161" # HOL Seattle, WA end end 

我只是硬编码一些地址,但你可以做任何你想做的事情。

我有同样的问题。 以下是我使用地理编码器实现的方法。

 #gemfile gem 'httparty', :require => 'httparty', :group => :development #application_controller def request_ip if Rails.env.development? response = HTTParty.get('http://api.hostip.info/get_html.php') ip = response.split("\n") ip.last.gsub /IP:\s+/, '' else request.remote_ip end end #controller ip = request_ip response = Geocoder.search(ip) 

(代码部分来自geo_magic gem的hostip.info,并基于此问题的其他答案。)

现在你可以做一些像response.first.state

这是地理编码器1.2.9的更新答案,为开发和测试环境提供硬编码IP。 只需将它放在config/initilizers/geocoder.rb的底部:

 if %w(development test).include? Rails.env module Geocoder module Request def geocoder_spoofable_ip_with_localhost_override ip_candidate = geocoder_spoofable_ip_without_localhost_override if ip_candidate == '127.0.0.1' '1.2.3.4' else ip_candidate end end alias_method_chain :geocoder_spoofable_ip, :localhost_override end end end 

你也可以这样做

 request.safe_location