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 をバンプする必要があります)。