Skip to content

Categories:

Posts tagged by Twitter

Twitter on Rails

twitteronrails.jpg


สวัสดีทุกท่าน วันนี้จะมาสอนเรื่องการใช้ 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 << %(
  • #{tweet.text} #{time_ago_in_words(tweet.createdat)} ago via #{tweet.source}
  • ) end rescue content << %(
  • Twitter is down again!
  • ) end content end end

    แล้วก็เรียก helper method นี้ใน view ก็จะได้ feed จาก Twitter ง่ายๆครับ

    Posted in Tutorial