Post tweet using omniauth-twitter and twitter Rails 3

Let’s get started

Before you must do install ‘devise’, First start adding this gem to your Gemfile:

  gem 'omniauth-twitter'
  gem 'twitter'

tell OmniAuth about this provider. For a Rails app :

config/initializers/devise.rb

Devise.setup do |config|
  require "omniauth-twitter"
  config.omniauth :twitter, "CONSUMER_KEY", "CONSUMER_SECRET"

  require 'devise/orm/active_record'
end

Replace CONSUMER_KEY and CONSUMER_SECRET with the appropriate values you obtained from
dev.twitter.com earlier and setting your apps in twitter like this

dev_twitter

Create new controller in your Rails apps

apps/controller/users/omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def twitter
    @user = User.find_for_twitter_oauth(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", kind: "Twitter"
      sign_in_and_redirect @user, event: :authentication
    else
      session["devise.twitter_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end  
end

config/routes.rb

 devise_for :users, :controllers => { omniauth_callbacks: "users/omniauth_callbacks" }

And your model user.rb

class User < ActiveRecord::Base  
  CONSUMER_KEY = 'WHAT_IS_YOUR_CONSUMER_KEY'
  CONSUMER_SECRET = 'WHAT_IS_YOUR_CONSUMER_SECRET'
  OPTIONS = {site: "http://api.twitter.com", request_endpoint: "http://api.twitter.com"}
  
  devise:omniauthable

  def self.find_for_twitter_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info
    if user = User.where(username: data.screen_name).first
      user
    else # Create a user with a stub password.
      User.create!(full_name: data.name, username: data.screen_name, provider: access_token.provider,
        token: access_token.credentials.token, token_secret: access_token.credentials.secret,
        password: Devise.friendly_token[0,20])
    end
  end

  def post_tweets(message)
    Twitter.configure do |config|
      config.consumer_key = User::CONSUMER_KEY
      config.consumer_secret = User::CONSUMER_SECRET
      config.oauth_token = self.authentication_token
      config.oauth_token_secret = self.authentication_token_secret
    end
    client = Twitter::Client.new
    begin
      client.update(message)
      return true
    rescue Exception => e
      self.errors.add(:oauth_token, "Unable to send to twitter: #{e.to_s}")
      return false
    end
  end
end

Let’s try….

class HomeController < ApplicationController
  def index
    current_user.post("post by gem 'twitter'")
  end
end