Display a Twitter feed from a Rails app

katherine picture katherine · Apr 16, 2012 · Viewed 9.5k times · Source

I have been able to have a user sign in with Twitter via OmniAuth (I followed Railscast #235-6 and made a simple application). Now I am trying to display the Twitter feed of the logged in user. Can anyone tell me how this is done? How do I initialize Twitter? How do I pass in the username and password of the logged in user? I am new to Rails so it would be helpful if I knew exactly where to put the code. Thanks

Answer

user24359 picture user24359 · Apr 16, 2012

First, you don't need user credentials to get a Twitter feed if it's public. Look at the Twitter gem. Once you install the gem, all you need to do is:

require 'twitter'
Twitter.user_timeline("icambron")

Try it out in IRB to get started. Pretty easy, right?

Now, you probably want to use your API key because Twitter limits anonymous requests, and it can be problematic from a shared server. Do that in an initializer:

Twitter.configure do |config|
  config.consumer_key = YOUR_CONSUMER_KEY
  config.consumer_secret = YOUR_CONSUMER_SECRET
  config.oauth_token = YOUR_OAUTH_TOKEN
  config.oauth_token_secret = YOUR_OAUTH_TOKEN_SECRET
end

Get the actual values from your Twitter developer page.

Finally, to get really fancy, if you want to scale up, you can make the request on behalf of the user, using the OAuth credentials that you got from OmniAuth (NOT their username and password; you don't have those). That will allow you to make a lot more requests per second, because they're coming from different users. Just initialize Twitter with the consumer_key and consumer_secret fields set to the stuff you got from the OmniAuth hash (see here, look under "credentials" to see how to get them from OmniAuth).