Display a Twitter feed from a Rails application

I was able to log in using Twitter via OmniAuth (I followed Railscast # 235-6 and made a simple application). Now I'm trying to display the Twitter feed of the logged-in user. Can someone tell me how to do this? How to initialize Twitter? How to transfer the username and password of a registered user? I am new to Rails, so it would be helpful if I knew exactly where to place the code. Thanks

+7
source share
2 answers

First, you don’t need user credentials to get Twitter feed if it is open. Look at Twitter Twitter . After installing the gem, all you have to do is:

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

Try on IRB to get started. Pretty easy, right?

Now, you probably want to use your API key because Twitter restricts anonymous requests, and this can be problematic from a shared server. Do this in the 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 the Twitter developer page.

Finally, to really like it, if you want to scale up, you can make a request on behalf of the user using the OAuth credentials you received from OmniAuth (NOT their username and password, you do not have these). This will allow you to make more requests per second, because they come from different users. Just initialize Twitter with the consumer_key and consumer_secret fields set for the things you got from the OmniAuth hash (see here , see the credentials section to see how to get them from OmniAuth).

+17
source

class tweet

  BASE_URL = "http://api.twitter.com/1.1/statuses/user_timeline.json" SCREEN_NAME = "OMGFacts" MAX_TWEETS = 10000 CONSUMER_KEY = "PMiAyrY5cASMnmbd1tg" CONSUMER_SECRET = "0TYRYg0hrWBsr1YZrEJvS5txfA9O9aWhkEqcRaVtoA" class << self def base_url BASE_URL end def screen_name SCREEN_NAME end def url(count = MAX_TWEETS) params = {:screen_name => screen_name, :count => count} [base_url, params.to_param].join('?') end def prepare_access_token(oauth_token, oauth_token_secret) consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, { :site => "http://api.twitter.com", :scheme => :header, }) # now create the access token object from passed values token_hash = { :oauth_token => oauth_token, :oauth_token_secret => oauth_token_secret, :open_timeout => 500000000 } access_token = OAuth::AccessToken.from_hash(consumer, token_hash ) return access_token end def get(count = MAX_TWEETS) count = Preference.get(:2000).to_i access_token = prepare_access_token("178394859-cJlRaiQvqVusPAPjqC2Nn7r3Uc7wWsGua7sGHzs","3T8LCZTYXzuPLGzmWX1yRnKs1JFpfJLKemoo59Piyl8") response = JSON.parse access_token.request(:get, url).body response[0...count] end end end 
0
source

All Articles