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

时间:2013-09-16 08:29:13

标签: ruby-on-rails ip-address development-environment rails-geocoder

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

我尝试了that,但它不起作用。我遇到以下错误:

.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 个答案:

答案 0 :(得分: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'(不能保证它适用于早期版本 - 你需要检查它的源代码或碰撞宝石)。

答案 1 :(得分:3)

这是正确答案:

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

答案 2 :(得分:1)

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

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

重新启动服务器。

答案 3 :(得分: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