andrew makes things

a blog about programming, machine learning, and whatever else I'm working on

How to Make Your Rails App Tweet the Twitter

| Comments

Suppose you want to build a Rails application for tracking popular links, and you want it to post the most popular links to Twitter automatically. This quick tutorial will show you how to do that using the newest version of the Ruby twitter gem. A little while ago I added the ability for Freebies Finder to tweet popular freebies. I recently had to do this for another site and decided that a tutorial was in order.

Setup the accounts

We’ll pretend that our website is called Signup for two Twitter accounts, AwesomeLinks and AwesomeLinksDev. We need to create a Twitter application through which our website can post to these accounts. Do this by logging into AwesomeLinks and visiting Select ‘Client’ as the Application Type, skip the Callback URL, and select Read & Write access. Twitter will give you a OAuth Consumer key and secret, which you will soon need.

Getting your OAuth Token and Secret

Now you need to authorize your new Twitter Application to post on both of your Twitter accounts. For this, we use a script:

(If you used the Twitter gem in the past, you may have used authorize_from_access for this, but that no longer works. We now have to require and use oauth separately.)

Fill in your Twitter Application’s Consumer key and secret and run the script. You will be prompted to visit a URL and then to enter the PIN that Twitter provides. Do this for both of your new Twitter accounts and record the results in config/twitter.yml, like so:

Initializing the Twitter gem

Now, create an initializer in config/initializers/twitter.rb and again include your Twitter App’s key and secret:

(If you want to Tweet to multiple accounts, you can do this differently and instead make separate Twitter::Client objects, each with their own OAuth tokens.)

Tweeting the Twitter

Finally, it’s time to augment our Link model so that it can send tweets. I decided to have it tweet the link’s description and a shortened version of its URL using the following code:

The rest is up to you. You could write a cronjob to automatically call tweet! on every link, or only on those with enough popularity. Have fun!