geo.rb 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright (C) 2012-2013 Zammad Foundation, http://zammad-foundation.org/
  2. class Observer::User::Geo < ActiveRecord::Observer
  3. observe 'user'
  4. def before_create(record)
  5. check_geo(record)
  6. end
  7. def before_update(record)
  8. check_geo(record)
  9. end
  10. # check if geo need to be updated
  11. def check_geo(record)
  12. location = ['street', 'zip', 'city', 'country']
  13. # check if geo update is needed based on old/new location
  14. if record.id
  15. current = User.where( :id => record.id ).first
  16. return if !current
  17. current_location = {}
  18. location.each { |item|
  19. current_location[item] = current[item]
  20. }
  21. end
  22. # get full address
  23. next_location = {}
  24. location.each { |item|
  25. next_location[item] = record[item]
  26. }
  27. # return if address hasn't changed and geo data is already available
  28. return if ( current_location == next_location ) && record.preferences['lat'] && record.preferences['lng']
  29. # geo update
  30. self.geo_update(record)
  31. end
  32. # update geo data of user
  33. def geo_update(record)
  34. address = ''
  35. location = ['street', 'zip', 'city', 'country']
  36. location.each { |item|
  37. if record[item] && record[item] != ''
  38. address = address + ',' + record[item]
  39. end
  40. }
  41. # return if no address is given
  42. return if address == ''
  43. # lookup
  44. latlng = GeoLocation.geocode( address )
  45. return if !latlng
  46. # store data
  47. record.preferences['lat'] = latlng[0]
  48. record.preferences['lng'] = latlng[1]
  49. end
  50. end