问题
I'm a newbie developer a little mystified/overwhelmed by the documentation. I'm wondering how to implement the Twitter gem in a Rails 3.1 application.
I have the gem installed and know that I need to configure it, but where would I put this configuration information in a rails application? and would it need to be altered in some way to get it synched with the rails app?
Twitter.configure do |config| config.consumer_key = ENV['CONSUMER_KEY'] config.consumer_secret = ENV['CONSUMER_SECRET'] config.oauth_token = ENV['ACCESS_TOKEN'] config.oauth_token_secret = ENV['TOKEN_SECRET'] end
do I have to require 'twitter' anywhere?
If I want visitors to my app to be update their status from my app, do I have to install Omniauth? or will this gem be sufficient? i.e. if I require 'twitter' in the gem file and do bundle install, will bundler take care of everything I need?
回答1:
First question, are you using devise? If you are, this should be easier, as I'm building my own app with devise + omniauth + twitter. If you aren't, even though I'm a newbie rails developer myself, I'll try to steer you in the right path.
For starters, you should have a twitter account. You should then login here and create your app. There, in the Settings
tab you can choose the type of access or permissions you want to your user's twitter accounts. In my case, I'm using Read only
, that is, I'm only using Twitter for authentication. Since you may want your users to update their statuses, you might want to take a look at the other 2 options: Read and Write
and Read, Write and Access direct messages
. You should also define a callback URL which is where Twitter returns after a successful authentication. Then you have several cosmetic options to pretty up your oauth dialog.
In the Details
tab, you'll find your Consumer key
and Consumer secret
which you should never reveal and which you'll need in your Rails app.
In your app, you should be including these gems (and running bundle install
afterwards):
#Gemfile
gem 'omniauth'
gem 'omniauth-twitter'
Then, in your initializers, you should create a file called omniauth.rb
(you can call it whatever you like, but it's the standard) with the following:
#config/initializers/omniauth.rb
require 'omniauth-twitter'
config.omniauth :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
In my case, since I'm using devise, I included this in my devise.rb
file, but it really doesn't matter where you include this as long as it's in a file in the config/initializers
directory.
You should definitely take a look at the following sites:
Omniauth's Github Wiki
The invaluable Railscasts by Ryan Bates
来源:https://stackoverflow.com/questions/8548888/how-to-set-up-the-twitter-gem-in-rails-app