Rails4:deviseとomniauthでTwitterログイン機能を実装する(その1)

詰まっててできていないんだけど、最初の方だけ投稿しておくことにした。

1. 必要なGemを入れる

Gemfileに追記する

# Gemfile
gem 'devise'
gem 'omniauth'
gem 'omniauth-twitter'
$ bundle install

2. Developerサイトでアプリを作成する

https://dev.twitter.com/

My Applications > Create New Appから作成する。

Website: http://www.localhost:3000
Callback URL: http://127.0.0.1:3000/auth/twitter/callback

にしておく。適当でも動くらしい...

・アプリを作成後、Access levelをRead and writeにしておく。
API keyとAPI secretをメモしておく。

3. deviseをインストールする

$ rails g devise:install
Warning: Running `gem pristine --all` to regenerate your installed gemspecs (and deleting then reinstalling your bundle if you use bundle --path) will improve the startup performance of Spring.
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:

       config.action_mailer.default_url_options = { host: 'localhost:3000' }

     In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

  4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:

       config.assets.initialize_on_precompile = false

     On config/application.rb forcing your application to not access the DB
     or load models when precompiling your assets.

  5. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

===============================================================================

config/environments/development.rbにDeviseからメール送信する際のデフォルトURLを追記する

#config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost:3000' } 

config/initializers/devise.rbに先ほど取得したkeyを追記する

#config/initializers/devise.rb 
require "omniauth-twitter" 
config.omniauth :twitter, "API key", "API secret"

続きは次回!ドットインストールか!