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

Bla*_*man 13 ruby ruby-on-rails geocode

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

request.location.ip显示"127.0.0.1"

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

Sea*_*ker 21

一个很好的干净方法是使用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
Run Code Online (Sandbox Code Playgroud)

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

config.middleware.use('SpoofIp', '64.71.24.19')
Run Code Online (Sandbox Code Playgroud)

  • @DickieBoy,你是对的,由于以下[更改](https://github.com/alexreisner/geocoder/commit/f67defd8d2b25511023be21c318aef42562058b2),该方法不适用于Geocoder 1.1.6.该解决方案使env ['HTTP_X_FORWARDED_FOR'] = nil,但它不会从哈希中删除密钥,因此通过`location`方法选择它,并且地理编码器执行nil搜索.在我的案例中评论该行是有效的. (6认同)

jes*_*iss 5

为此,我经常使用params[:ip]或正在开发中.这允许我测试其他IP地址的功能,并假装我在世界的任何地方.

例如

class ApplicationController < ActionController::Base
  def request_ip
    if Rails.env.development? && params[:ip]
      params[:ip]
    else
      request.remote_ip
    end 
  end
end
Run Code Online (Sandbox Code Playgroud)