Wednesday, 8 May 2013

Twitter gem for Rails : How to share dynamic contents to Twitter from your Rails Application

Before going through this post . I would suggest you to go through my previous FB share  post. You will get to know the basic functionality & working from the prev post .After that please go through Twitter gem description.

I hope you have gone through the prev post and you have got some idea about it.

Now we will start with Twitter share implementation.You have to include  "twitter" & "oauth" gems into your Gemfile.

gem 'twitter'

gem 'oauth'

Compared to FB share , here we need to include "Oauth" gem for authenticating the user to twitter and redirect the user back to your applications Callback action.After getting the Oauth Secret Key i.e returning from Twitter you can configure the Twitter gem settings and you can post to twitter from your Rails app.
Route : 


  match "/twitter_share/auth" => "twitter_share#auth"  , :method => :get , :as => :twitter_auth

  match "/twitter_share/callback" => "twitter_share#callback"  , :method => :post , :as => :twitter_callback



Twitter Share Controller & Actions :


 def auth

    cookies["title"] = { :value => "#{params[:title]}", :expires => 1.minute.from_now }

    cookies["url"] = { :value => "#{params[:url]}", :expires => 1.minute.from_now }

 
    consumer_key = "APP ID"

    consumer_secret = "SECRET KEY"

    oauth_consumer = OAuth::Consumer.new(consumer_key, consumer_secret,

      :site => 'http://api.twitter.com',

      :request_endpoint => 'http://api.twitter.com',

      :sign_in => true)

    request_token = oauth_consumer.get_request_token(:oauth_callback => "http://#{request.host_with_port}/twitter_share/callback")


    session[:request_token] = request_token.token

    session[:request_token_secret] = request_token.secret

    redirect_to request_token.authorize_url

  end

  def callback 

    consumer_key = "APP ID"

    consumer_secret =  "SECRET KEY"

    oauth_consumer = OAuth::Consumer.new(consumer_key, consumer_secret,

      :site => 'http://api.twitter.com',

      :request_endpoint => 'http://api.twitter.com',

      :sign_in => true)

    r_token = session[:request_token]

    r_stoken = session[:request_token_secret]

    atoken = OAuth::RequestToken.new(oauth_consumer,r_token, r_stoken).get_access_token(:oauth_verifier => params[:oauth_verifier])


    Twitter.configure do |conf|

      conf.consumer_key = consumer_key

      conf.consumer_secret = consumer_secret

      conf.oauth_token = atoken.token

      conf.oauth_token_secret = atoken.secret

    end

    Twitter.update("My new post on  #{cookies["title"]}  #{cookies["url"]}")

    redirect_to root_path

  end




No comments:

Post a Comment