Skip to content

Instantly share code, notes, and snippets.

@vierarb
Last active August 29, 2015 14:04
Show Gist options
  • Save vierarb/4fe26007bc3b198b4d0b to your computer and use it in GitHub Desktop.
Save vierarb/4fe26007bc3b198b4d0b to your computer and use it in GitHub Desktop.
Foursquare Places
class FoursquarePlace
include Cacheable
ATTRIBUTES = %i(pid name street city country latitude longitude icon
categories)
def initialize(attrs = {})
@connection = FoursquareConnector.new
_initialize_attributes!(attrs)
end
def attributes
instance_values.except('place').except('connection')
end
def pid
@place.id
end
def name
@place.name
end
def street
@place.location.address
end
def city
@place.location.city
end
def country
@place.location.country
end
def latitude
@place.location.lat
end
def longitude
@place.location.lng
end
def icon
@place.categories.blank? ? default_icon_url : icon_url
end
def categories
@place.categories.map(&:name)
end
private
def _initialize_attributes!(attrs)
@place = attrs[:place] ? attrs[:place] : search(attrs[:pid])
_normalize!
end
def _normalize!
ATTRIBUTES.each do |key|
instance_variable_set("@#{key}", send(key))
end
end
def search(pid)
cache_object([:places, pid], expiration: expiration) do
@connection.retrieve { |foursquare| foursquare.venue(pid) }
end
end
# Number of seconds
# 1 day = 86400 seconds
def expiration
86_400 * 30
end
def default_icon_url
url = Rails.application.secrets.aws[:url]
bucket = Rails.application.secrets.aws[:bucket]
path = 'request_images'
image = 'no_category.png'
[url, bucket, path, image].join('/')
end
def icon_url
return nil if @place.categories.blank?
icon = @place.categories.first.icon.prefix
icon << 88
icon << @place.categories.first.icon.suffix
end
end
class FoursquarePlaces
def initialize
@connection = FoursquareConnector.new
end
def search(attrs = {})
attrs = default_attributes.merge(attrs)
places = @connection.retrieve do |foursquare|
foursquare.search_venues(attrs)
end.try(:venues)
_normalize_array!(places)
end
private
def _normalize_array!(places)
places.map { |place| _normalize!(place) } if places
end
def _normalize!(place)
FoursquarePlace.new(place: place)
end
def default_attributes
{
ll: '40.4167750,-3.7037900',
categoryId: '4bf58dd8d48988d1d8941735',
radius: default_radius,
limit: default_limit,
intent: default_intent
}
end
def default_radius
10_000
end
def default_limit
50
end
def default_intent
:browse
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment