I am calculating the distance between a site and stores using Haversine gem.
Since the latitude and the longitude of a store can be nil
, I want to test if this is the case the value calculated in my hash to be return should be a string like that: "no precision address".
I wrote this method and it works perfectly, still only the point of nil
address:
require 'haversine'
class Api::V1::Angular::SitesController < Api::ApplicationController
# GET /api/v1/angular/sites/:id/distances
def stores_distances
site = Site.find params[ :id ]
distances = Store.current.map do |store|
{
name: store.name,
value: Haversine.distance(
site.address.latitude,
site.address.longitude,
store.address.latitude,
store.address.longitude
).round(2)
}
end
render json: {
distances: distances.to_json
}
end
end
How about?
def stores_distances
site = Site.find params[ :id ]
distances = Store.current.map do |store|
value = Haversine.distance(
site.address.latitude,
site.address.longitude,
store.address.latitude,
store.address.longitude
).round(2) || 'no precision address'
{
name: store.name,
value: value
}
end
render json: {
distances: distances.to_json
}
end
When your Haversine.distance
is nil then the OR
kicks in and the string is set for value.
Basing on Dave comment:
def stores_distances
site = Site.find params[ :id ]
distances = Store.current.map do |store|
{
name: store.name,
value: distance(site.address, store.address) || 'no precision address'
}
end
render json: {
distances: distances.to_json
}
end
def distance(site_address, store_address)
return nil unless store_address.latitude && store_address.longitude
Haversine.distance(
site_address.latitude,
site_address.longitude,
store_address.latitude,
store_address.longitude
).round(2)
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.