[英]Create Rails Proxy for JSON
I want to asynchronously query the Foursquare API, which currently does not allow for the old $.get(). 我想异步查询Foursquare API,该API当前不允许使用旧的$ .get()。 My short term solution is to make a Helper that just GETs the data like so: 我的短期解决方案是创建一个仅获取数据的Helper,如下所示:
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. 那行得通,但是我宁愿使它成为我可以在页面加载后通过jQuery AJAX请求获得的代理,以加快处理速度。 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. 我很确定该帮助程序与使代理工作所需要做的事情很接近,但是我不确定我需要在哪里放置代理JSON以便能够使用jQuery进行获取。
Am I on the right track for creating the proxy with net/http? 我是否在使用net / http创建代理的正确轨道上?
Where do I put the proxy on my side so that I can access it with a jQuery GET? 我在哪里将代理放在一边,以便可以使用jQuery GET访问它?
I think using Net::HTTP is good enough for this. 我认为使用Net :: HTTP足以满足要求。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.