Skip to content

Instantly share code, notes, and snippets.

@johnhamelink
Created March 14, 2016 13:05
Show Gist options
  • Select an option

  • Save johnhamelink/87a432de7b216eb83914 to your computer and use it in GitHub Desktop.

Select an option

Save johnhamelink/87a432de7b216eb83914 to your computer and use it in GitHub Desktop.
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