开发环境中地理编码器的假IP

Flo*_*ahl 2 development-environment ruby-on-rails ip-address rails-geocoder

我想替换开发环境中的127.0.0.1 IP,以便手动测试地理编码器gem.我怎样才能做到这一点 ?

我想的,但它不工作.我遇到以下错误:

.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0.rc1/lib/active_support/infle??ctor/methods.rb:226:in 'const_get': uninitialized constant SpoofIp (NameError)
Run Code Online (Sandbox Code Playgroud)

Exi*_*iRe 5

我的回答并不适合所有人,因为我只想在request.location本地测试.但如果你想做同样的事情,那么我有适合你的解决方案.首先,让我向您展示.location方法的源代码:

module Geocoder
  module Request

    def location
      @location ||= begin
        detected_ip = env['HTTP_X_REAL_IP'] || (
          env['HTTP_X_FORWARDED_FOR'] &&
          env['HTTP_X_FORWARDED_FOR'].split(",").first.strip
        )
        detected_ip = IpAddress.new(detected_ip.to_s)
        if detected_ip.valid? and !detected_ip.loopback?
          real_ip = detected_ip.to_s
        else
          real_ip = self.ip
        end
        Geocoder.search(real_ip).first
      end
      @location
    end
  end
end

# ...
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,有变量,detected_ip并找到它的数据宝石检查env['HTTP_X_REAL_IP'].那么,现在我们可以在控制器中轻松存根:

class HomeController < ApplicationController    
  def index
    env['HTTP_X_REAL_IP'] = '1.2.3.4' if Rails.env.development?
    location = request.location

    # => #<Geocoder::Result::Freegeoip:0x007fe695394da0 @data={"ip"=>"1.2.3.4", "country_code"=>"AU", "country_name"=>"Australia", "region_code"=>"", "region_name"=>"", "city"=>"", "zipcode"=>"", "latitude"=>-27, "longitude"=>133, "metro_code"=>"", "area_code"=>""}, @cache_hit=nil> 
  end
end
Run Code Online (Sandbox Code Playgroud)

它适用于地理编码器'1.2.5'(不能保证它适用于早期版本 - 你需要检查它的源代码或碰撞宝石).