adopt-a-hydrant/app/models/thing.rb

33 lines
975 B
Ruby
Raw Normal View History

2013-12-31 18:51:53 +00:00
require 'geokit'
class Thing < ActiveRecord::Base
2014-08-15 00:16:19 +00:00
extend Forwardable
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)
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
FROM things
ORDER BY distance
LIMIT ?
SQL
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
def reverse_geocode
2013-12-31 18:51:53 +00:00
@reverse_geocode ||= Geokit::Geocoders::MultiGeocoder.reverse_geocode([lat, lng])
end
def adopted?
!user.nil?
end
2011-02-23 20:50:59 +00:00
end