Hi,This is tutorial about implement twitter oauth in Ruby on Rails application using twitter_oauth gem.

You can see installation from http://github.com/moomerman/twitter_oauth/. The gem author show how to implement the oauth call in command prompt.

Now I’ll show you how to use the gem via web browser and save access key into database.

1. Create rails application ( if it’s your 1st rails project you should google about ruby on rails app )

2. Implement the restful authentication plugin ( see http://github.com/technoweenie/restful-authentication ) until you have user system.

3. Install the twitter_oauth gem http://github.com/moomerman/twitter_oauth/

4. Create migration

class CreateTwitterAccounts < ActiveRecord::Migration

  def self.up
    create_table :twitter_accounts do |t|
      t.integer :user_id
      t.string :token
      t.string :secret
      t.timestamps
    end
  end

  def self.down
    drop_table :twitter_accounts
  end
end

5. Edit user model, add this line

  has_one  :twitter_account, :dependent => :destroy

  def has_twitter_oauth?
    self.twitter_account and self.twitter_account.token and self.twitter_account.secret
  end

  def create_or_update_twitter_account_with_oauth_token(token, secret)
    twitter_account = self.twitter_account ? self.twitter_account : TwitterAccount.new(:user_id => self.id)
    twitter_account.token = token
    twitter_account.secret = secret
    twitter_account.save!
  end

6. Create and edit Model twitter_account ( ruby script/generate model twitter_account )
   Add this line: 

   belongs_to :user

7. Create try controller ( ruby script/generate controller try )
8 Edit try controller and copy-paste this:

   # require the gem twitter_oauth
   require 'twitter_oauth'
   # need user logged in
   before_filter :login_required

   #initialize your twitter key and secret ( you can get from here http://apiwiki.twitter.com/ )
   TWITTER_KEY = '83evR5lsb0E1gmvn0FXacQ'
   TWIITER_SECRET = 'REuY5OAS6EFXrC4KYCKYLX68qVBmx4lJshTZehIfI2M'

   # The url to back when user has authorize your app
   TWITTER_CALLBACK_URL = 'http://localhost:3000/try/callback'

    #index method
    # this method check if user has authorize your app
    # if no it'll show they link to authorize your app in their twitter account
    def index
      if !current_user.has_twitter_oauth?
        @T_OAUTH = TwitterOAuth::Client.new( :consumer_key => TWITTER_KEY, :consumer_secret => TWIITER_SECRET )
        @T_REQUEST_TOKEN = @T_OAUTH.request_token :oauth_callback => TWITTER_CALLBACK_URL
        @T_TOKEN = @T_REQUEST_TOKEN.token
        @T_SECRET = @T_REQUEST_TOKEN.secret
        @link = @T_REQUEST_TOKEN.authorize_url
        session['token' ] = @T_TOKEN
        session['secret'] = @T_SECRET
     end
  end

  # Method callback
  # this method will call after user authorize your app in twitter website
  # this method will authorize oauth token and verifier send from twitter and if success key and secret will stored in database
  def callback
    @T_OAUTH = TwitterOAuth::Client.new(:consumer_key => TWITTER_KEY, :consumer_secret => TWIITER_SECRET )
    @oauth_verifier = params[:oauth_verifier]
    access_token = @T_OAUTH.authorize(session['token'], session['secret'], :oauth_verifier => @oauth_verifier)
    if (@result = @T_OAUTH.authorized?)
      current_user.create_or_update_twitter_account_with_oauth_token(access_token.token, access_token.secret)
      session['token'] = nil
      session['secret'] = nil
      flash[:notice] = "Authorize complete"
    else
      flash[:notice] = "Authorize failed"
    end

    rescue
      flash[:notice] = "Authorize failed"
  end

  # method update status
  # this method is for sent tweet to your twitter
  def update_status
    if current_user.has_twitter_oauth?
      @T_OAUTH = TwitterOAuth::Client.new( :consumer_key => TWITTER_KEY,
      :consumer_secret => TWIITER_SECRET, :token => current_user.twitter_account.token,
      :secret => current_user.twitter_account.secret )

      if @T_OAUTH.authorized? and @T_OAUTH.update(params[:status])
        flash[:notice] = "Your tweet has been sent"
      else
        flash[:notice] = "Sorry ! Your tweet failed to sent, try later !"
      end
    else
      flash[:notice] = "You dont have twitter account with oauth token, please authorize myapp in your twitter !"
    end

   redirect_to :action => 'index' 

 end
9. Add file index.html.erb in app/views/try
    Copy - paste

    Test Twitter API

     <% if @link %>
        You have not authorize my app into your twitter 

       <%= link_to "Click here to authorize myapp.me", @link %>
     <% else %>
        Try to update your status 

        <% form_tag "/try/update_status", :method => "post" do %>
          <%= text_field_tag "status" %>
          <%= submit_tag "Update" %>
        <% end %>
      <% end %>

10. Add file callback.html.erb in app/views/try
   copy - paste

   <%= flash[:notice] %>

   <%= link_to "Click here", "/try" %> to back

Hope it can help you..
Please let me know if you find any errors or problems when implement the codes.

Comments on: "Simple code to test twitter oauth with ruby on rails via web browser" (9)

  1. Great Work Feb, Sounds Great, would you mind to create it as plugin and upload to your GitHub😀 thanks.

  2. Munendra said:

    Hi Thanks for such an awesome tutorial. I am actually new to oAuth. But for me it took just 15 mins to create the app and running. I havent used the restful_authentication though in my example. It is really useful.

    Is there any similar oAuth gem available for Facebook as well?

  3. I have implement this application .by this i got pin number..
    can u plz explain now with this pin number ,what to do next??

    • febyartandi said:

      The “pin” you got from twitter is “oauth_verifier”.

      You can use it for get access_token with this:
      access_token = @T_OAUTH.authorize(session[‘token’], session[‘secret’], :oauth_verifier => @oauth_verifier)

  4. Hi,

    In the twitters controller, in the new action, this code is giving me a problem:

    “access_token = @client.authorize(
    oauth_token,
    oauth_secret
    )”

    If i comment it out, it says “Your account has been authorized at Twitter,” but it really hasn’t. If I leave the code in, I get “There was an error…”

    • febyartandi said:

      HI Greg,

      May you show me your twitters_controller
      and error stack trace ? So, I can help you to fix your problem

      Thanks,

  5. Wow! Thank you! My spouse and i continuously desired to write on my net internet site at the same time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: