0

I'm trying to display my own twitter timeline on my website, i've created code that works fine on the console but when I try to do this on my application I get the whole response body rather than just the tweets' text.

P.S. I'm trying to do this from scratch for learning purposes using NET::HTTP rather than httParty or the twitter gem.

I'm doing the request through the controllers' helper.

def twitter_timeline
    baseurl = "https://api.twitter.com"
    path = "/1.1/statuses/user_timeline.json"
    query = URI.encode_www_form("screen_name" => "twitterapi", "count" => 5)

    address = URI("#{baseurl}#{path}?#{query}")
    request = Net::HTTP::Get.new address.request_uri

    def print_tweets(tweets)
       tweets.each do |tweet|
         puts tweet["text"]
       end
    end

    http = Net::HTTP.new address.host, address.port
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER

    consumer_key ||= OAuth::Consumer.new("SECRET", "SECRET")
    access_token ||= OAuth::Token.new("SECRET","SECRET")

    request.oauth! http, consumer_key, access_token
    http.start
    response = http.request request

    tweets = nil

    if response.code == '200' then
       tweets = JSON.parse(response.body)
       print_tweets(tweets)
    end

    nil
end

Then I call it on the view like so:

<%= twitter_timeline %>
Andrii Furmanets
  • 1,081
  • 2
  • 12
  • 29
gimiarn1801
  • 131
  • 2
  • 7
  • Why do you have `print_tweets` nested in `twitter_timeline`? That doesn't make any sense. Anyway, you should **return** the formatted string that you want to display from your `twitter_timeline` method. **Don't use `puts` in your method.** – Mischa Feb 25 '14 at 14:32
  • @mischa When I use `return` I only get the last tweet not the requested 5 – gimiarn1801 Feb 25 '14 at 14:38
  • 1
    You have to build a string of 5 tweets and then return it. Right now you seem to be iterating over the tweets and finally returning only the last one, disregarding the previous four. You have to do something like this: `return tweets.map { |tweet| tweet['text'] }.join("\n\n")`. And then use `simple_format` to format the timeline: `<%= simple_format(twitter_timeline) %>`. – Mischa Feb 25 '14 at 14:42

1 Answers1

0

The easiest way is to use the embedded timeline feature https://dev.twitter.com/docs/embedded-timelines

André Barbosa
  • 518
  • 4
  • 17