Created
November 12, 2011 19:12
-
-
Save r38y/1360969 to your computer and use it in GitHub Desktop.
Wraps call to api endpoint for returning objects for a map based on some parameters.
This file contains 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
class Api::CirclesController < ApplicationController | |
def index | |
circles_presenter = API::CirclesPresenter.new(params) | |
render :json => circles_presenter.to_json, | |
:callback => params[:callback] | |
end | |
end |
This file contains 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
class API::CirclesPresenter | |
extend ActiveSupport::Memoizable | |
def initialize(params={}) | |
@ne = params[:ne] | |
@sw = params[:sw] | |
@pt = params[:pt] | |
@rad = params[:rad] | |
end | |
attr_accessor :ne, :sw, :pt, :rad | |
def as_json | |
{ :circles => circles, :count => count } | |
end | |
def to_json | |
Rails.cache.fetch(cache_key, :expires_in => expires_in) do | |
as_json.to_json | |
end | |
end | |
def circles | |
circles = if bounding_box? | |
Circle.all_in_bounding_box(sw, ne) | |
elsif point_and_radius? | |
Circle.all_in_radius(pt, rad) | |
else | |
Circle.all | |
end | |
circles.map{|c| API::CirclePresenter.new(c).as_json} | |
end | |
memoize :circles | |
def count | |
if bounding_box? | |
Circle.count_in_bounding_box(sw, ne) | |
elsif point_and_radius? | |
Circle.count_in_radius(pt, rad) | |
else | |
Circle.count | |
end | |
end | |
memoize :count | |
def cache_key | |
pieces = ['circles'] | |
if bounding_box? | |
pieces << 'ne' << ne | |
pieces << 'sw' << sw | |
elsif point_and_radius? | |
pieces << 'pt' << pt | |
pieces << 'rad' << rad | |
else | |
pieces << 'all' | |
end | |
pieces.join('/') | |
end | |
def bounding_box? | |
ne && sw | |
end | |
def point_and_radius? | |
pt && rad | |
end | |
def expires_in | |
if bounding_box? || point_and_radius? | |
1.hour | |
else | |
nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment