Skip to content

Instantly share code, notes, and snippets.

@brett-richardson
Created August 3, 2013 11:28
Show Gist options
  • Save brett-richardson/6146143 to your computer and use it in GitHub Desktop.
Save brett-richardson/6146143 to your computer and use it in GitHub Desktop.
ApplicationController < ActionController::Base
# Fetch the best location available to the app at the time
def fetch_location
if params[:location].present? # Geocode the manual location input
session[:manual_location] = Geokit::Geocoders::MultiGeocoder.geocode( params[:location] )
end
if session[:manual_location].present?
session[:manual_location]
elsif current_user && current_user.city.present? # Use the user profile
current_user
else # Fallback to IP location
session[:geo_location] ||= Geokit::Geocoders::MultiGeocoder.geocode(
if Rails.env.production? || Rails.env.staging?
request.remote_ip
else # Development environments
'217.43.175.61'
end
)
end
end
end
class Post < ActiveRecord::Base
DISTANCE_SCALE = 20.0
acts_as_mappable
scope :by_time, order( 'created_at DESC' )
scope :by_distance, lambda { |origin|
geo_scope( :origin => origin ).order(
'CASE WHEN distance IS null THEN 1 ELSE 0 END, distance'
)
}
scope :by_distance_time, lambda{ |origin, datetime|
geo_scope( :origin => origin ).order(
"( CASE WHEN distance IS null THEN distance ELSE 9999 END * ? ) * ABS(
DATEDIFF( posts.created_at, ? )
) DESC",
DISTANCE_SCALE,
datetime
)
}
end
class PostsController < ApplicationController
def index
@posts = Post.by_time_distance( fetch_location, Time.now )
render :json => @posts
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment