Wednesday, 29th February 2012 - 0 Comments
Hey - good to see you! If you are new here, you can subscribe to the RSS feed for updates on this topic.
I'm a relative newcomer to the Ruby/Rails world. I'd not had the need to add Twitter to a site before, but I had an interesting scenario yesterday trying to Tweet from one of my project sites via Twitter/OAuth. Here's how I did it.
I spent a good deal of my afternoon yesterday ploughing through the Twitter API documentation as well as figuring out OAuth. Hopefully this brief tutorial will stop you having to pull your hair out if you want to start allowing users to Tweet from your web page.
The first thing you need to do is register your app with the Twitter API at https://dev.twitter.com, making sure to select read and write access when creating an app. I missed this at first, having selected read only. The important parts here are to make sure that your callback URL is correct. It needs to be of the form:
For local testing you may need to replace yourdomain.com with 127.0.0.1:3000 (for local Rails apps started on the Rails server with the default port). Make sure you do NOT use localhost:3000, it does not work.
You will need to install the OAuth Ruby gem in your project/gemset:
Note: Better installation instructions can be found here.
Once that is installed, you need to go through the token preparation process in your Ruby code. This means obtaining the Consumer token and secret keys from the Twitter Developers site for your application, then adding them into the following code:
The above function will need to be included into an app/helper or similar include file if you are using a web framework such as Rails. The parameters to the function are the OAuth tokens given to you by the user when authenticated to your service (via Omniauth or some other mechanism). The "APIKey" and "APISecret" are your application's consumer keys which you obtain from the Twitter Dev site.
In order to actually Tweet as an authenticated user who is signed into your service you will need to prepare a token and then perform a request again the Twitter API. Here is the correct request to use to post a Tweet, via an account of an authenticated user:
Where the token and secret are, as stated above, the user's Twitter OAuth keys that you will obtain on sign in to your service.
At this point, you can start experimenting with additional parameters to your update_hash, such as entities (images, links etc) and in reply to links. The following provide some good docs/tutorials on the subject: