geek-peachの日記

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

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

では、第1回の続き。

 

 

config/initializers/omniauth.rb にTwitterのコンシューマキーとシークレットを記述。

Twitterアプリのプロバイダ情報を記述。

(ここの意味がまだあまりわかっていない。

コンシューマキーとシークレットはわかるんだが・・・)

 

Rails.application.config.middleware.use OmniAuth::Builder do

  provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'

end

 

 

第一回の最後に表示された画面の「Sign in with Twitter」をクリックすると、

Twitterのアプリを許可するかという画面が現れる。(上記のomniauth.rbを書かないとエラーになる。)

そして、その画面でアプリを許可してから戻ってくる画面をこれから作っていく。

 

戻ってきた画面では、テキストボックスを用意し、そこにつぶやく内容を入力する。

ついでに、つぶやいた内容をDBに保存させる。

DBを使うときに便利なscaffoldを使って、一気にモデルと画面を作成する!

 

# rails g scaffold t_line tweet_str:string tweet_by:string

 

scaffoldでテンプレートを作ったら、以下のファイルを修正する。

・app/controllers/t_lines_controller.rb

・app/controllers/sessions_controller.rb

・app/views/t_lines/_form.html.erb

・app/views/t_lines/index.html.erb

・db/migrate/XXXXXXXXXXXXXX_create_users.rb

・config/routes.rb

 

それぞれ中身は以下の通り。

 

このアプリのメインとなるつぶやきとDB格納を行う部分。

つぶやきはcreateメソッドのなかで行なっています。

・app/controllers/t_lines_controller.rb

 

class TLinesController < ApplicationController

  # GET /t_lines

  # GET /t_lines.json

  def index

    @t_lines = TLine.all

    @tmp = 1

 

    respond_to do |format|

      format.html # index.html.erb

      format.json { render json: @t_lines }

    end

  end

 

  # GET /t_lines/1

  # GET /t_lines/1.json

  def show

    @t_line = TLine.find(params[:id])

 

    respond_to do |format|

      format.html # show.html.erb

      format.json { render json: @t_line }

    end

  end

 

  # GET /t_lines/new

  # GET /t_lines/new.json

  def new

    @t_line = TLine.new

 

    respond_to do |format|

      format.html # new.html.erb

      format.json { render json: @t_line }

    end

  end

 

  # GET /t_lines/1/edit

  def edit

    @t_line = TLine.find(params[:id])

  end

 

  # POST /t_lines

  # POST /t_lines.json

  def create

    @t_line = TLine.new(params[:t_line])

    @t_line.tweet_by = current_user.name

 

    Twitter.configure do |config|

      config.consumer_key       = " CONSUMER_KEY "

      config.consumer_secret    = " CONSUMER_SECRET"

      config.oauth_token        = current_user.token

      config.oauth_token_secret = current_user.secret

    end

 

    twitter_client = Twitter::Client.new

    twitter_client.update(@t_line.tweet_str)

 

    respond_to do |format|

      if @t_line.save

        format.html { redirect_to @t_line, notice: 'T line was successfully created.' }

        format.json { render json: @t_line, status: :created, location: @t_line }

      else

        format.html { render action: "new" }

        format.json { render json: @t_line.errors, status: :unprocessable_entity }

      end

    end

  end

 

  # PUT /t_lines/1

  # PUT /t_lines/1.json

  def update

    @t_line = TLine.find(params[:id])

 

    respond_to do |format|

      if @t_line.update_attributes(params[:t_line])

        format.html { redirect_to @t_line, notice: 'T line was successfully updated.' }

        format.json { head :no_content }

      else

        format.html { render action: "edit" }

        format.json { render json: @t_line.errors, status: :unprocessable_entity }

      end

    end

  end

 

  # DELETE /t_lines/1

  # DELETE /t_lines/1.json

  def destroy

    @t_line = TLine.find(params[:id])

    @t_line.destroy

 

    respond_to do |format|

      format.html { redirect_to t_lines_url }

      format.json { head :no_content }

    end

  end

end

 
 
・app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def callback
    auth = request.env["omniauth.auth"]
    user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
    session[:user_id] = user.id
    redirect_to :controller => 't_lines', :action => 'new'
  end
 
  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Signed out!"
  end
 
end
 
 
下の_form.html.erbはtweet_byフィールドを表示しないようにコメントアウトしているだけ
・app/views/t_lines/_form.html.erb 

  

<%= form_for(@t_line) do |f| %>

  <% if @t_line.errors.any? %>

    <div id="error_explanation">

      <h2><%= pluralize(@t_line.errors.count, "error") %> prohibited this t_line from being saved:</h2>

 

      <ul>

      <% @t_line.errors.full_messages.each do |msg| %>

        <li><%= msg %></li>

      <% end %>

      </ul>

    </div>

  <% end %>

 

  <div class="field">

    <%= f.label :tweet_str %><br />

    <%= f.text_field :tweet_str %>

  </div>

<!--

  <div class="field">

    <%= f.label :tweet_by %><br />

    <%= f.text_field :tweet_by %>

  </div>

-->

  <div class="actions">

    <%= f.submit %>

  </div>

<% end %>

 

 

 

・app/views/t_lines/index.html.erb

<h1>Listing t_lines</h1>

 

<table>

  <tr>

    <th>Tweet str</th>

    <th>Tweet by</th>

    <th></th>

    <th></th>

    <th></th>

  </tr>

 

<% @t_lines.each do |t_line| %>

  <tr>

    <td><%= t_line.tweet_str %></td>

    <td><%= t_line.tweet_by %></td>

    <td><%= link_to 'Show', t_line %></td>

    <td><%= link_to 'Edit', edit_t_line_path(t_line) %></td>

    <td><%= link_to 'Destroy', t_line, confirm: 'Are you sure?', method: :delete %></td>

  </tr>

<% end %>

</table>

<br />

<%= link_to 'New T line', new_t_line_path %>

 

 

・config/routes.rb

SampleTwitter::Application.routes.draw do

  resources :t_lines

 

  get "sessions/index"

 

  match '/auth/:provider/callback' => 'sessions#callback'

  match "/signout" => "sessions#destroy", :as => :signout

 

  root :to => "sessions#index"

end
 
 
ユーザを格納するDBを作成
# rails g model user
 
以下2つのファイルを修正する。
・app/models/user.rb
class User < ActiveRecord::Base
  # attr_accessible :title, :body
  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth["provider"]
      user.uid = auth["uid"]
 
      if auth['info']
        user.name = auth['info']['name'] || ""
        user.screen_name = auth["info"]["nickname"]
      end
      user.token = auth['credentials']['token']
      user.secret = auth['credentials']['secret']
    end
  end
end
 
 

・ db/migrate/XXXXXXXXXXXXXX_create_users.rb

 

class CreateUsers < ActiveRecord::Migration

  def self.up

    create_table :users do |t|

      t.string :provider, :null => false

      t.string :uid, :null => false

      t.string :screen_name, :null => false, :uniq => true

      t.string :name, :null => false

      t.string :token

      t.string :secret

 

      t.timestamps

    end

    add_index :users, [:provider, :uid]

    add_index :users, [:screen_name]

  end

 

  def self.down

    drop_table :users

  end

end

 
ファイルの修正後以下を実行。
# rake db:migrate
 
第1回同様以下のようにサービスにアクセス
# rails s
http://<プロジェクトのURL>/ (route.rbにルートの設定をしたので/にアクセス出来る)
 
このままだと、ログアウトできなかったり色々不具合はあるが、そこは改良して下さい。
なにか変なところがあれば教えていただけると助かります。