Ruby: Rails で Twitter アプリ

Rails 4.0.2 で新規作成

$ rails new tweettest

 

Twitter 用の gem を追加

Gemfile

gem 'omniauth-twitter'
gem 'twitter'

Gem: OmniAuth Twitter
https://github.com/arunagw/omniauth-twitter
Gem: Twitter
http://rdoc.info/gems/twitter

$ bundle install

 

Developers Site でアプリを登録

https://dev.twitter.com

Callback URL を下記のような感じで設定

http://127.0.0.1:3000/auth/twitter/callback

「Read and Write」と「Signed in Twitter」にチェック

 

OmniAuth 用のイニシャライザーを用意

Ruby: config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, "コンシューマーキー", "コンシューマーシークレット"
end

 

アプリケーションコントローラーにヘルパーメソッドを定義

Ruby: app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  # signed_in ヘルパーメソッドを追加
  helper_method :signed_in?
  
  private
  def signed_in?
    true if session[:oauth_token]
  end
end

 

アプリケーションビューにサインイン・アウトを定義

Erb: app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
  <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<div id="user-sign-status">
<% if signed_in? %>
	Welcome <%= session[:username] %>!
	<%= link_to "Sign Out", "/signout" %>
<% else %>
	<%= link_to "Sign in with Twitter", "/auth/twitter" %>
<% end %>
</div>

<%= yield %>

</body>
</html>

 

ルートを定義

Ruby: config/routes.rb

Tweettest::Application.routes.draw do
  root :to => "tweet#input"
  get "tweet/input"
  post "tweet/update"
  get "/auth/:provider/callback" => "sessions#create"
  get "/signout" => "sessions#destroy"
end

 

SessionsController を作成

Ruby: app/controllers/sessions_controler.rb

class SessionsController < ApplicationController
  def create
    auth = request.env["omniauth.auth"]
    session[:oauth_token] = auth.credentials.token
    session[:oauth_token_secret] = auth.credentials.secret
    session[:username] = auth.extra.access_token.params[:screen_name]
    redirect_to root_url, :notice => "Signed in!"
  end

  def destroy
    session[:oauth_token] = nil
    session[:oauth_token_secret] = nil
    session[:username] = nil
    redirect_to root_url, :notice => "Signed out!"
  end
end

 

Twitter 投稿用の Controller を作成

Ruby: tweet_controller.rb

class TweetController < ApplicationController
  def input
  end

  def update
    if signed_in?
      client = Twitter::REST::Client.new do |config|
  	config.consumer_key         = "コンシューマーキー"
	config.consumer_secret      = "コンシューマーシークレット"
        config.access_token         = session[:oauth_token]
        config.access_token_secret  = session[:oauth_token_secret]
      end
      client.update(params[:message])
      @result = :success
    else
      @result = :not_signed_in
    end
  end
end

 

Twitter 投稿用の View を作成

Erb: app/views/tweet/input.html.erb

<h1>Twitter Sample Application</h1>
<p>Enter a message:</p>
<%= form_tag({:action => "update"}, {:method => "post"}) do %>
  <%= text_field_tag(:message) %>
  <%= submit_tag("Submit") %>
<% end %>

 

Twitter 投稿後の View を作成

Erb: app/views/tweet/update.html.erb

<%= link_to "HOME" , root_url %>