debugrubyrailsMinor
Nested trial and error in if-else condition
Viewed 0 times
errorconditionelsenestedandtrial
Problem
Using Rails 3.2, I have the following:
If the first geocoding with address fails, it will try latitude and longitude. If still fails, then it logs error, else it will save.
Is this a good way to write this code?
g = Geocoder.search(address)
# if no address found, geocode with latitude and longitude
if g.empty?
g = Geocoder.search(latitude, longitude)
if g.empty?
log.info "Geocode failed for #{latitude}, #{longitude}"
end
else
---save---
endIf the first geocoding with address fails, it will try latitude and longitude. If still fails, then it logs error, else it will save.
Is this a good way to write this code?
Solution
Some notes:
I'd write:
g: use meaningful names.
- Don't mix code with parentheses and without.
- Check the pattern Object#presence.
# if no address found, ...: declarative code makes this kind of comments unnecessary.
I'd write:
results = Geocoder.search(address).presence || Geocoder.search(latitude, longitude)
if results.present?
# save
else
log.info("Geocode failed for addr='#{search}' and coords=#{latitude}/#{longitude}")
endCode Snippets
results = Geocoder.search(address).presence || Geocoder.search(latitude, longitude)
if results.present?
# save
else
log.info("Geocode failed for addr='#{search}' and coords=#{latitude}/#{longitude}")
endContext
StackExchange Code Review Q#41241, answer score: 6
Revisions (0)
No revisions yet.