
สวัสดีทุกท่าน วันนี้จะมาสอนเรื่องการใช้ Twitter API อย่างง่ายใน Ruby on Rails ครับ อันดับแรกเลย
gem install twitter
ครับ
จากนั้นใน ApplicationHelper ให้สร้าง method "show_tweet" ดังข้างล่าง
require 'twitter'
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def show_tweet
username = 'your_twitter_username'
password = 'your_password'
content = ''
begin
httpauth = Twitter::HTTPAuth.new(username,password)
#@tweets = Twitter::Base.new(httpauth).friends_timeline(:count=>5)
@tweets = Twitter::Base.new(httpauth).user_timeline(:count=>5)
for tweet in @tweets
content << %(
<li class="twit"><span>#{tweet.text}</span>
<a href="http://twitter.com/#{username}/statuses/#{tweet.id}">#{time_ago_in_words(tweet.created_at)} ago</a>
via #{tweet.source}</li>
)
end
rescue
content << %(
<li class="twit">Twitter is down again!</li>
)
end
content
end
end
แล้วก็เรียก helper method นี้ใน view ก็จะได้ feed จาก Twitter ง่ายๆครับ
Tags: RoR | Rails | Twitter | Programming |

