geek-peachの日記

geekを目指してpeachが頑張るブログ。実行したコマンドやデータ分析についてメモっていく

rails3.2.3でTwitterにログインしてつぶやくサンプルAP(第1回)

こちらで使っている環境

CentOS 5.7

ruby 1.9.3p125

Rails 3.2.3

・gem 1.8.21

 

とにかくまず、プロジェクトの作成

rails new sample_twitter

 

Gemfileに以下を加える

gem 'omniauth'

gem 'execjs'

gem 'therubyracer'

gem 'omniauth-twitter'

gem 'twitter'

 

# bundle install

 

まずは、認証してログインする部分のコントローラを作る。

# rails g controller sessions index

 

■ app/views/sessions/index.html.erbを以下のように編集

<% if current_user %>

  Welcome <%= current_user.name %>!<br>

  <%= link_to "Sign Out", signout_path %>

<% else %>

  <%= link_to "Sign in with Twitter", "/auth/twitter" %>

<% end %>

 

 ■ app/controllers/application_controller.rbを以下のように修正

class ApplicationController < ActionController::Base

  protect_from_forgery

 

  helper_method :current_user

 

  private

 

  def current_user

    @current_user ||= User.find(session[:user_id]) if session[:user_id]

  end

end

 

ここまでちゃんとできていれば、

# rm public/index.html

でindex.htmlを消す。(残っていると/へのアクセスはroute.rbの記述よりindex.htmlが優先される。)

# rails s によりWebServerを起動し、

http://<プロジェクトのURL>/sessions/index

 にアクセスすれば画面が表示されるはず。。。

 

<続く>