I want to asynchronously query the Foursquare API, which currently does not allow for the old $.get(). My short term solution is to make a Helper that just GETs the data like so:
def foursquare_info_for(venue_id)
res = Net::HTTP.get_response("api.foursquare.com", "/v1/venue.json?vid=#{venue_id}")
data = JSON.parse(res.body)
info = Hash.new
info["mayor_name"] = "#{data['venue']['stats']['mayor']['user']['firstname']} #{data['venue']['stats']['mayor']['user']['lastname']}"
info["mayor_photo_src"] = "#{data['venue']['stats']['mayor']['user']['photo']}"
info["checkins"] = "#{data['venue']['stats']['checkins']}"
info
end
That works, but I'd rather make this a proxy that I can get to with a jQuery AJAX request after the page loads to speed things up a bit. I'm pretty sure this helper is close to what I need to do to get a proxy working, but I'm not sure where I need to put the proxy JSON on my side in order to be able to grab it with jQuery.
Am I on the right track for creating开发者_开发问答 the proxy with net/http?
Where do I put the proxy on my side so that I can access it with a jQuery GET?
I think using Net::HTTP is good enough for this.
I would make a class for it. Something like:
class FoursquareInfo < Struct.new(:venue_id)
def info
{ :mayor_name => mayour_name, :mayor_photo_src => mayor_photo_src, :checkins => checkins }
end
def mayor_name
"#{mayor_firstname} #{mayor_lastname}"
end
def mayor_firstname
mayor["firstname"]
end
def mayor
stats["mayor"]["user"]
end
def stats
data["venue"]["stats"]
end
def data
@data ||= JSON.parse(response.body)
end
def response
Net::HTTP.get_response("api.foursquare.com", "/v1/venue.json?vid=#{venue_id}")
end
# etc...
end
And from a controller:
class FoursquareInfosController < ApplicationController
def show
render :json => FoursquareInfo.new(params[:id]).info
end
end
精彩评论