Hey guys! Recently, I just performed a little research to make a twitter connection from a rails app. So for you guys, who wants to make a simple app with twitter connection in it, I think this one might help. Before you set all this up, you need to make sure that you already have registered a new application at http://dev.twitter.com. Just to be safe, set the permission for your consumer key and oauth token are read and write. And don’t forget to check the checkbox “Allow this application to be used to Sign in with Twitter”. If it’s all set up, then you just follow this step to set things up at your rails app.
First thing, you need to add these gems to your
gem 'twitter' gem 'twitter-login', '~> 0.4.1', :require => 'twitter/login'
Don’t forget to run
bundle install command to make sure that you already have the gems.
Next, add a new file in your
config/initiliazers folder (let’s say we name it with
twitter.rb) which is containing these codes
Twitter.configure do |config| config.consumer_key = YOUR_CONSUMER_KEY config.consumer_secret = YOUR_CONSUMER_SECRET config.oauth_token = YOUR_OAUTH_TOKEN config.oauth_token_secret = YOUR_OAUTH_TOKEN_SECRET end
FYI, that code will be used for twitter gem to make all connection to twitter API. The access provided depends on what permission you have for your consumer key. If you have read, write, and DM access, that means you have all access.
Okay, that setting is the only configuration that we need to make the API access and next is twitter login. There are some configurations that you need to add to your app such as :
- Open your
config/application.rband add this code
config.twitter_login = Twitter::Login.new :consumer_key => YOUR_CONSUMER_KEY, :secret => YOUR_CONSUMER_SECRET
- Open your
config/routes.rband add this code
twitter = Yourapp::Application.config.twitter_login twitter_endpoint = twitter.login_handler(:return_to => '/home') #you can change where twitter will bring you back to the app after finishing the sign in process mount twitter_endpoint => 'login', :as => :login
- Open your
app/controllers/application_controller.rband add this code
#these codes can be modified depends on your needs include Twitter::Login::Helpers def current_user session[:twitter_user] ||= twitter_user end helper_method :current_user def logged_in? !!current_user end helper_method :logged_in?
If you have set all up, you can add these codes to your view to run a test:
<a href=">%= login_path %<" id="twitter-login" data-method="post">Twitter Login</a> <br> <% if logged_in? %> <%= current_user %> <% end %>
Now you try it and after you click the link, you’ll see the data which is your app retrieved from twitter. It’s cool, isn’t it?