It was the big things weeks ago, but I didn’t had time to test it. Twitter_auth, allows you to user the twitter authentication on you application. And it’s really sweet!.
Let’s do a small implementation together.
h2. Step 1: Prepare your development box
Because Twitter doesn’t allow the callback parameter anymore, you’ll need to setup your workstation.
I recommend to install passenger in your development box, and use the hosts file to manage your different applications.
For that, just follow the official passenger doc. Easy peasy.
Then you’ll need to prepare your localhost. I like to work with [applicationName].local.
sudo nano /etc/hosts
Then add an extra line
Now create your rails app
rails -d mysql twitterauth
or take my source code my github twitterauth-test ;)
Finally add the site to apache
sudo nano /etc/apache2/sites-enabled/twitterauth
Then copy (and modify) these lines on it
DocumentRoot "/home/[REPLACE WITH YOU PATH]/twitterauth/public"
<directory "/home/[REPLACE WITH YOU PATH]/twitterauth/public">
Allow from all
sudo /etc/init.d/apache2 restart
You now have your development box working with passenger. Next application you’ll develop, just add a new line in the /etc/hosts file, a new site-enabled file restart apache and you’re ready.
h2. Step 2: Install twitter_auth as a depency
Modify you environement.rb by adding
config.gem 'twitter-auth', :lib => 'twitter_auth'
Then sudo rake gems:install, and you’ll have the gem installed.
h2. Step 3: Prepare the application
In order to work properly, your app (even on development mode) need to be registered on twitter. Visit Twitter apps and form with your informations.
Twitter doesn’t accept the callback param anyone, so you’ll need to provide http://twitterauth.local/oauth_callback as a callback in the configuration form.
When you save the informations, Twitter will give you 2 keys that need to be copied in config/twitter_auth.yml.
Your app is now ready!
h2. Step 4: Let’s do some code
We are going to create a twitter controller, with an index action
./script/generate controller Twitter index
Twitter_auth use the REST twitter api style, so to the loggued user friend time line copy and paste this in twitter_controller.rb, and returns a Json array. (visit the twitter api wiki for more informations)
Before calling functions that need you to be logged in, you’ll have to use the login_required method on before_filter.
This is going to be our root method so add in routes.rb
map.root :controller => "twitter"
This code goes into twitter_controller.rb
#Retreive the friend timeline
@tweets = current_user.twitter.get(‘/statuses/friends_timeline’)
Then in your views/twitter/index.html.rb
<% @tweets.each do |tweet| >
<li><= link_to(tweet[‘user’][‘screen_name’] + ‘:’, ‘http://twitter.com/’ + tweet[‘user’][‘screen_name’], :target => ‘_blank’) + tweet[‘text’] ></li>
< end -%></ul>
After a bit of CSS, if you open http://twitterauth.local you should have something like this