freegeoip.rb 683 B

12345678910111213141516171819202122232425262728
  1. # Copyright (C) 2012-2013 Zammad Foundation, http://zammad-foundation.org/
  2. require 'faraday'
  3. require 'cache'
  4. class GeoIp::Freegeoip
  5. def self.location(address)
  6. # check cache
  7. cache_key = "freegeoip::#{address}"
  8. cache = Cache.get( cache_key )
  9. return cache if cache
  10. # do lookup
  11. host = "http://freegeoip.net"
  12. url = "/json/#{CGI::escape address}"
  13. data = {}
  14. begin
  15. conn = Faraday.new( :url => host )
  16. response = conn.get url
  17. data = JSON.parse( response.body )
  18. Cache.write( cache_key, data, { :expires_in => 90.days } )
  19. rescue
  20. Cache.write( cache_key, data, { :expires_in => 60.minutes } )
  21. end
  22. data
  23. end
  24. end