Created
March 14, 2016 13:05
-
-
Save johnhamelink/87a432de7b216eb83914 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module DistanceScopable | |
| extend ActiveSupport::Concern | |
| included do | |
| # Select a specified distance from the coordinate of the table (in meters) | |
| scope :distance_to_point, lambda { |table_name: self.table_name, srid: 4326, lat: nil, lng: nil, distance: 5000| | |
| fail 'Attributes missing' if distance.nil? || lat.nil? || lng.nil? || srid.nil? | |
| select(<<-SQL.squish | |
| ST_Distance( | |
| #{table_name}.coordinates, | |
| ST_GeographyFromText('SRID=#{srid};POINT(#{lng} #{lat})') | |
| ) as distance | |
| SQL | |
| ) | |
| } | |
| scope :where_distance_within, lambda { |table_name: self.table_name, coordinate: {}, distance: 5000| | |
| fail 'Attributes missing' if distance.nil? || coordinate.nil? || coordinate.empty? | |
| where(<<-SQL.squish | |
| ST_DWithin( | |
| #{table_name}.coordinates, | |
| ST_GeographyFromText('SRID=#{coordinate[:srid]};POINT(#{coordinate[:lng]} #{coordinate[:lat]})'), | |
| #{distance} | |
| ) | |
| SQL | |
| ) | |
| } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment