3

我想替换开发环境中的 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)
4

4 回答 4

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

# ...

如您所见,存在变量detected_ip并要查找它的数据 gem 签出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

它适用于地理编码器“1.2.5”(不能保证它适用于早期版本 - 您需要查看源代码或碰撞 gem)。

于 2014-10-14T08:10:46.360 回答
3

这是正确的答案:

class ActionDispatch::Request
  def remote_ip
    "1.2.3.4"
  end
end
于 2013-12-17T19:08:02.037 回答
1

将此添加到您的 config/environments/development.rb。

class ActionController::Request
  def remote_ip
    "1.2.3.4"
  end
end

重新启动您的服务器。

于 2013-09-17T09:27:53.510 回答
0

这是地理编码器 1.2.9 的更新答案,为开发和测试环境提供硬编码 IP:

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
于 2015-08-24T19:33:30.250 回答