Dinshaw Raje
Dinshaw Raje

Reputation: 963

Geocoder gem creating issue in heroku server

Hello I have included following gem in my gemfile

gem 'geocoder'

and written following code in my view file

- @location = Geocoder.search(request.remote_ip).first.country
%div{"class" => "currentCountry", "value" => "#{@location}"}
- if session[:browser] == 'mobile'
  testmobile
- else
  testdesktop

and in heroku server it gives me error while in my local server its working fine.

ActionView::Template::Error (undefined method `country' for nil:NilClass):
2016-02-16T07:47:14.447459+00:00 app[web.1]: 
2016-02-16T07:47:14.447455+00:00 app[web.1]:     3: - if session[:browser] == 'mobile'
2016-02-16T07:47:14.447456+00:00 app[web.1]:     4:   = render 'mobile'
2016-02-16T07:47:14.447457+00:00 app[web.1]:   app/views/spree/checkout/edit.html.haml:1:in `_b6865a451d7a5a040f6c1f6376727300'
2016-02-16T07:47:14.447458+00:00 app[web.1]: 
2016-02-16T07:47:14.447454+00:00 app[web.1]:     1: - @location = Geocoder.search(request.remote_ip).first.country
2016-02-16T07:47:14.447454+00:00 app[web.1]:     2: %div{"class" => "currentCountry", "value" => "#{@location}"}

Please guide why I am facing this error in heroku server.

Upvotes: 1

Views: 298

Answers (2)

sghosh968
sghosh968

Reputation: 601

I went through this before, its because the request is getting timed out and the response is nil. The reasons are :-

  • :ip_lookup(default- freegeoip)
  • :timeout(default- 3 seconds)

Freegeoip as its a free service is usually overloaded and sometimes might respond late and as the default timeout is set as 3 seconds the request gets timedout and it returns nil as a response which causes this issue(same has been discussed here).

Solutions :-

  • switch to some paid ip lookup service(other options here) to get better and faster service.(recommended)
  • continue with freegeoip but increase the timeout to 7-8 seconds so that the request won't get timedout soon(not recommended for production applications)

Both the options ip_lookup and timeout can be configured in the initializer (check here for more information, thanks.

Upvotes: 1

Dias
Dias

Reputation: 882

geocoder_result = Geocoder.search(request.remote_ip)

@location = geocoder_result.empty? ? "" : geocoder_result.first.country

Upvotes: 1

Related Questions