Sam*_*lks 2 ruby ruby-on-rails xmlhttprequest ruby-on-rails-3
因此,我试图将Twitter上的推文放入rails应用程序(请注意,因为这是一项我不能使用Twitter Gem的任务)而且我很困惑.我可以以JSON字符串的形式获取我需要的推文,但我不知道从那里去哪里.我知道我正在制作的Twitter API调用返回一个带有一堆Tweet对象的JSON数组,但我不知道如何获取推文对象.我尝试过JSON.parse,但仍无法获取所需的数据(我不确定返回的是什么).这是我到目前为止的代码,我已经用注释/字符串清楚地表达了我正在尝试的内容.我是Rails的新手,所以这可能是我想要做的事情.
def get_tweets
require 'net/http'
uri = URI("http://search.twitter.com/search.json?q=%23bieber&src=typd")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
case response
when Net::HTTPSuccess then #to get: text -> "text", date: "created_at", tweeted by: "from_user", profile img url: "profile_img_url"
JSON.parse(response.body)
# Here I need to loop through the JSON array and make n tweet objects with the indicated fields
t = Tweet.new(:name => "JSON array item i with field from_user", :text "JSON array item i with field text", :date => "as before" )
t.save
when Net::HTTPRedirection then
location = response['location']
warn "redirected to #{location}"
fetch(location, limit - 1)
else
response.value
end
end
Run Code Online (Sandbox Code Playgroud)
谢谢!
JSON.parse方法返回表示json对象的ruby散列或数组.在你的情况下,Json被解析为哈希,带有"结果"键(里面有你的推文)和一些元数据:"max_id","since_id","refresh_url"等.参考twitter文档有关返回字段的说明.再次以你的例子为例:
parsed_response = JSON.parse(response.body)
parsed_response["results"].each do |tweet|
t = Tweet.new(:name => tweet["from_user_name"], :text => tweet["text"], :date => tweet["created_at"])
t.save
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5069 次 |
| 最近记录: |