To integerate twitter with your existing rails application follow the steps below:-
- Install required Gem as sudo gem install Twitter.
- Register your application in read-write mode with Twitter.
- Note down the ConsumerToken and ConsumerSecret when application is registered on Twitter.
- Refer the attached controller to authorize user on Twitter using OAuth and update the status there.
app/twitters_controller.rb
class TwittersController < ApplicationController
#it is obtained from twitter when your application is registered
ConsumerToken, ConsumerSecret = 'consumer token', 'consumersecreat'
before_filter :verify_oauth, :only => [:share_status]
def share_status
begin
client.update("Voila! Status set from globallogic")
flash[:notice] = "Twitter status updated successfully"
rescue Exception => e
flash[:warning] = "Status is duplicate/invalid"
end
redirect_to root_path
end
def finalize
oauth.authorize_from_request(session['rtoken'], session['rsecret'], params[:oauth_verifier])
#profile = Twitter::Base.new(oauth).verify_credentials
session['rtoken'] = session['rsecret'] = nil
session[:atoken] = oauth.access_token.token
session[:asecret] = oauth.access_token.secret
redirect_to session[:redirect_to]
end
private
def oauth
@oauth ||= Twitter::OAuth.new(ConsumerToken, ConsumerSecret, :sign_in => false)
end
def client
oauth.authorize_from_access(session[:atoken], session[:asecret])
Twitter::Base.new(oauth)
end
def verify_oauth
if session[:atoken].blank? or session[:asecret].blank?
session[:redirect_to] = {:controller => params[:controller], :action => params[:action]}
oauth.set_callback_url(finalize_twitters_url)
session['rtoken'] = oauth.request_token.token
session['rsecret'] = oauth.request_token.secret
redirect_to oauth.request_token.authorize_url
end
end
end
No comments:
Post a Comment