3

ジオコーダー gem を手動でテストするために、開発環境にある 127.0.0.1 IP を置き換えたいと考えています。どうやってやるの ?

私はそれを試しましたが、うまくいきません。次のエラーが発生します。

.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 に答える