2013-12-31 18:51:53 +00:00
|
|
|
require 'geokit'
|
|
|
|
|
2011-09-15 21:41:26 +00:00
|
|
|
class Thing < ActiveRecord::Base
|
2014-08-15 00:16:19 +00:00
|
|
|
extend Forwardable
|
2012-11-15 17:34:19 +00:00
|
|
|
include ActiveModel::ForbiddenAttributesProtection
|
2011-02-23 20:50:59 +00:00
|
|
|
belongs_to :user
|
2014-08-15 00:16:19 +00:00
|
|
|
def_delegators :reverse_geocode, :city, :country, :country_code,
|
|
|
|
:full_address, :state, :street_address, :street_name,
|
|
|
|
:street_number, :zip
|
2011-05-22 14:35:46 +00:00
|
|
|
has_many :reminders
|
2014-04-01 08:15:29 +00:00
|
|
|
validates :city_id, uniqueness: true, allow_nil: true
|
|
|
|
validates :lat, presence: true
|
|
|
|
validates :lng, presence: true
|
2011-02-23 20:50:59 +00:00
|
|
|
|
2014-04-01 08:15:29 +00:00
|
|
|
def self.find_closest(lat, lng, limit = 10)
|
2011-04-04 05:49:23 +00:00
|
|
|
query = <<-SQL
|
2012-03-31 12:47:25 +00:00
|
|
|
SELECT *, (3959 * ACOS(COS(RADIANS(?)) * COS(RADIANS(lat)) * COS(RADIANS(lng) - RADIANS(?)) + SIN(RADIANS(?)) * SIN(RADIANS(lat)))) AS distance
|
2011-09-15 21:41:26 +00:00
|
|
|
FROM things
|
2011-04-04 05:49:23 +00:00
|
|
|
ORDER BY distance
|
|
|
|
LIMIT ?
|
|
|
|
SQL
|
2011-09-15 21:41:26 +00:00
|
|
|
find_by_sql([query, lat.to_f, lng.to_f, lat.to_f, limit.to_i])
|
2011-02-23 20:50:59 +00:00
|
|
|
end
|
2011-03-17 18:46:06 +00:00
|
|
|
|
2011-06-25 09:38:00 +00:00
|
|
|
def reverse_geocode
|
2013-12-31 18:51:53 +00:00
|
|
|
@reverse_geocode ||= Geokit::Geocoders::MultiGeocoder.reverse_geocode([lat, lng])
|
2011-06-25 09:38:00 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def adopted?
|
2013-12-02 22:52:37 +00:00
|
|
|
!user.nil?
|
2011-06-25 09:38:00 +00:00
|
|
|
end
|
2011-02-23 20:50:59 +00:00
|
|
|
end
|