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.

=begin -- comment begin ( make sure this is in the most left row /  indentation = 0 )

  def hallo
    render :text => "hello word"
  end

=end -- comment end ( make sure this is in the most left row /  indentation = 0 )

I’ve this problem when run my “old” rails application.

After some minutes trace, I found the problem is “name” for application controller file.

In my old application, the name is “application.rb“,

and when I renamed it with “application_controller.rb“,  it’s working !!

Hope this help people.

This post is describe how fixed the problem:

!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
C:/ruby/ruby-1.8.6/lib/ruby/gems/1.8/gems/mysql-2.7.3-x86-mswin32/ext/mysql.so: 998: Invalid access to memory location. – C:/ruby/ruby-1.8.6/lib/ruby/gems/1.8/gems/mysql-2.7.3-x86-mswin3
2/ext/mysql.so (LoadError)

That is the mysql bug.

Simple Solutions:

  1. Download the libmysql.zip from http://www.dll-files.com/dllindex/dll-files.shtml?libmysql
  2. Unzip libmysql.zip
  3. Copy paste libmysql.dll to “path_of_mysql/bin” Example: C:/xampp/mysql/bin
  4. Copy paste libmysql.dll to “path_of_ruby/bin” Example : C/ruby/bin

Thanks,

Tag Cloud