Skip to content

Commit

Permalink
Optimize nearby endpoint.
Browse files Browse the repository at this point in the history
The most common way the nearby endpoint would be used is to display
locations near the one currently being visited on a map. A client would
only need a few location attributes to make use of this endpoint, such
as the name, alternate name, latitude, longitude, address, and slug.

By creating a special serializer that only returns a few attributes, we
improve the performance of the nearby endpoint.
  • Loading branch information
Moncef Belyamani committed Oct 22, 2014
1 parent b5cb2fd commit 90ba868
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,8 @@ Style/GuardClause:

Rails/HasAndBelongsToMany:
Enabled: false

Style/AndOr:
# Whether `and` and `or` are banned only in conditionals (conditionals)
# or completely (always).
EnforcedStyle: conditionals
16 changes: 7 additions & 9 deletions app/controllers/api/v1/search_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,16 @@ def index

def nearby
location = Location.find(params[:location_id])

render json: [] and return if location.coordinates.blank?

radius = Location.validated_radius(params[:radius], 0.5)

nearby =
if location.coordinates.present?
location.nearbys(radius).
page(params[:page]).per(params[:per_page]).
includes(:organization, :address, :phones)
else
Location.none.page(params[:page]).per(params[:per_page])
end
nearby = location.nearbys(radius).
page(params[:page]).per(params[:per_page]).
includes(:address)

render json: nearby, status: 200
render json: nearby, each_serializer: NearbySerializer, status: 200
generate_pagination_headers(nearby)
end

Expand Down
5 changes: 5 additions & 0 deletions app/serializers/nearby_serializer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class NearbySerializer < ActiveModel::Serializer
attributes :id, :alternate_name, :latitude, :longitude, :name, :slug

has_one :address
end
6 changes: 6 additions & 0 deletions spec/api/nearby_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@
expect(json.first['name']).to eq('Belmont Farmers Market')
end

it 'returns a summarized JSON representation' do
get api_location_nearby_url(@loc, radius: 2, subdomain: ENV['API_SUBDOMAIN'])
expect(json.first.keys).
to eq %w(id alternate_name latitude longitude name slug address)
end

context 'with no radius' do
it 'displays nearby locations within 0.5 miles' do
get api_location_nearby_url(@loc, subdomain: ENV['API_SUBDOMAIN'])
Expand Down

0 comments on commit 90ba868

Please sign in to comment.