Search code examples
ruby-on-railsruby-on-rails-4geocodingrails-geocoder

Rails. Retriving country user is accessing from


I was wondering if anyone knows an alterntive to find out the country user is accessing from? So far I have been using 'geocoder' - wich turns out to be way too slow. The requests sent and retrieved adds a lot of time to server response time (between 600-800ms). Or perhaps I miss some sort of configuration?

If anyone has a better way of doing this, please let me know!

Thank you!

application.rb

def extract_locale_from_accept_language_header

  if cookies[:windhager_locale] && I18n.available_locales.include?(cookies[:windhager_locale].to_sym)
    l = cookies[:windhager_locale].to_sym
  else
    begin
      country_code = country_code = request.location.country_code
      if country_code
        country_code = country_code.downcase.to_sym
        case country_code
          when :en
            l = :int_en
          when :us
            l = :int_en
          when :ca
            # CHECK BROWSER LANGUAGE
            l = check_browser_language_ca
          when :nz
            l = :int_en
          when :au
            l = :int_en
          when :de
            l = :de
          when :fr
            l = :fr
          when :ch
            # CHECK BROWSER LANGUAGE
            l = check_browser_language_ch
          when :at
            l = :at
          when :li
            l = :ch_de
          when :rd
            l = :at
          else
            l = check_browser_language
        end
      else
        l = check_browser_language
      end
    rescue
      l = I18n.default_locale
    ensure
      cookies.permanent[:windhager_locale] = l
    end
  end

  return l
end

Solution

  • Assuming you're doing remote API calls right now, you could download an IP database from MaxMind and do local lookups instead of API calls. This method has worked quite well for my usecase. Checkout the documentation from the geocoder github page for additional details, but here is an example:

    Geocoder.configure(ip_lookup: :maxmind_local, maxmind_local: {file: File.join('folder', 'GeoLiteCity.dat')})