我想替换开发环境中的 127.0.0.1 IP,以便手动测试地理编码器 gem。我怎样才能做到这一点 ?
我试过了,但它不起作用。我遇到以下错误:
.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0.rc1/lib/active_support/inflector/methods.rb:226:in 'const_get': uninitialized constant SpoofIp (NameError)
我想替换开发环境中的 127.0.0.1 IP,以便手动测试地理编码器 gem。我怎样才能做到这一点 ?
我试过了,但它不起作用。我遇到以下错误:
.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0.rc1/lib/active_support/inflector/methods.rb:226:in 'const_get': uninitialized constant SpoofIp (NameError)
我的答案并不适合所有人,因为我只想在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)。
这是正确的答案:
class ActionDispatch::Request
def remote_ip
"1.2.3.4"
end
end
将此添加到您的 config/environments/development.rb。
class ActionController::Request
def remote_ip
"1.2.3.4"
end
end
重新启动您的服务器。
这是地理编码器 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