Skip to content

Instantly share code, notes, and snippets.

@kevinvangelder
Created February 23, 2013 01:24
Show Gist options
  • Save kevinvangelder/5017856 to your computer and use it in GitHub Desktop.
Save kevinvangelder/5017856 to your computer and use it in GitHub Desktop.
def dealers
return [] unless self.zip && self.distance
require 'haversine'
return @dealers if @dealers.present?
@dealers = []
# Convert zip to lat-long
starting_location = to_lat_long_hash(self.zip)
# Loop through all USA dealers that have a storefront_zip
temp_dealers = User.where("storefront_country = ? AND storefront_zip IS NOT NULL AND dealer = ?", "USA", true).all
temp_dealers.each do |d|
# Convert the zip code to a lat-long
storefront_location = to_lat_long_hash(d.storefront_zip)
# and check if the two lat-long sets are within the given distance
if Haversine.distance(starting_location, storefront_location).to_miles.to_i <= self.distance.to_i
@dealers << d
end
end
@dealers
end
def to_lat_long_hash(zip)
require 'area'
[zip.to_s.to_lat.to_f, zip.to_s.to_lon.to_f]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment