I can\'t get geocoder to work correct as my local ip address is 127.0.0.1 so it can\'t located where I am correctly.
The request.location.ip shows \"127.0.0.1\"
I implemented this slightly different, and this works well for my case.
In application_controller.rb
i have a lookup method which calls the Geocoder IP lookup directly passing in the results of request.remote_ip.
def lookup_ip_location
if Rails.env.development?
Geocoder.search(request.remote_ip).first
else
request.location
end
end
Then in config/environments/development.rb
i monkey-patched the remote_ip call:
class ActionDispatch::Request
def remote_ip
"71.212.123.5" # ipd home (Denver,CO or Renton,WA)
# "208.87.35.103" # websiteuk.com -- Nassau, Bahamas
# "50.78.167.161" # HOL Seattle, WA
end
end
I just hard code some addresses, but you could do whatever you'd like here.
For this I usually use params[:ip]
or something in development. That allows me to test other ip addresses for functionality and pretend I'm anywhere in the world.
For example
class ApplicationController < ActionController::Base
def request_ip
if Rails.env.development? && params[:ip]
params[:ip]
else
request.remote_ip
end
end
end
This is an updated answer for geocoder 1.2.9 to provide a hardcoded IP for development and test environments. Just place this at the bottom of your config/initilizers/geocoder.rb
:
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
I had the same question. Here is how I implemented with geocoder.
#gemfile
gem 'httparty', :require => 'httparty', :group => :development
#application_controller
def request_ip
if Rails.env.development?
response = HTTParty.get('http://api.hostip.info/get_html.php')
ip = response.split("\n")
ip.last.gsub /IP:\s+/, ''
else
request.remote_ip
end
end
#controller
ip = request_ip
response = Geocoder.search(ip)
( code part with hostip.info from geo_magic gem, and based on the other answer to this question. )
now you can do something like response.first.state
you may also do this
request.safe_location
A nice clean way to do it is using MiddleWare. Add this class to your lib directory:
# lib/spoof_ip.rb
class SpoofIp
def initialize(app, ip)
@app = app
@ip = ip
end
def call(env)
env['HTTP_X_FORWARDED_FOR'] = nil
env['REMOTE_ADDR'] = env['action_dispatch.remote_ip'] = @ip
@status, @headers, @response = @app.call(env)
[@status, @headers, @response]
end
end
Then find an IP address you want to use for your development environment and add this to your development.rb file:
config.middleware.use('SpoofIp', '64.71.24.19')