Guest User

Untitled

a guest
Jun 24th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. Geocoding Changes
  2.  
  3. def geocode_address
  4. geo=Geokit::Geocoders::MultiGeocoder.geocode (address)
  5. errors.add(:address, "Could not Geocode address") if !geo.success
  6. self.lat, self.lng = geo.lat,geo.lng if geo.success
  7. end
  8.  
  9.  
  10. That's an ugly method. 5 things that are wrong with it:
  11. 1. Use unless geo.success instead of [if !]
  12. 2. No need for the two if statements. Should be
  13. self.lat, self.lng = geo.lat, geo.lng if geo.success
  14. 3. Use self during assignment when referring to attributes
  15. 4. Indentation is dumb and wrong
  16. 5. I'm not sure if I missed it or covered it in problems 1-4/
  17.  
  18. According to geokit-rails README
  19.  
  20. acts_as_mappable :auto_geocode=>{:field=>:address, :error_message=>'Could not geocode address'}
  21.  
  22. is equivalent to
  23.  
  24. acts_as_mappable
  25. before_validation_on_create :geocode_address
  26.  
  27. So, if we want the location to be updated everytime a talk's location is changed, as is currently expressed in the before_save
  28. before_save :geocode_location, :if => proc {|talk| talk.location_changed?}
  29.  
  30. we can simply do the following instead
  31.  
  32. in Talk.rb
  33. acts_as_mappable
  34. before_validation :geocode_location, :if => proc {|talk| talk.location_changed? }
  35. include GeoKit::Geocoders
  36.  
  37. then the method becomes:
  38. private
  39.  
  40. def geocode_location
  41. loc = MultiGeocoder.geocode(self.location)
  42. self.lat, self.lng = loc.lat, loc.lng if loc.success
  43. end
  44.  
  45. All the tests still pass this way and it cleans up the code quite a bit.
  46.  
  47. Because this method (geocode_location) is used in Talk.rb, Speaker.rb, and Event.rb, it might be beneficial to pull this information into a module and include it where needed, to help keep the code DRY
Add Comment
Please, Sign In to add comment