Railsアプリから twitterにつぶやいてみた

http://tech.lampetty.net/tech/index.php/archives/323 を参考にtwitterへアクセスするRailsアプリを作ってみた。目標としては、診断メーカー で結果を twitterに投稿する部分だけを実現する感じで。

アプリケーション登録

最初に twitterへ作ろうとしているアプリケーションを登録しておく。
http://dev.twitter.com/apps/new へアクセスして Consumer KeyとConsumer Secretを入手。これは後からRailsのソースに書き込む。

項目はこんな感じで

  • アプリケーション名 : twitpost_nunocky (ユニークな名前を付ける必要がある)
  • アプリケーションの説明 : OAuth study (適当に)
  • アプリケーションのウェブサイトURL : http://www.example.com
  • 所属会社/団体 : sample
  • サイト : (空欄)
  • アプリケーションの種類 : ブラウザアプリ
  • コールバックURL : http://www.example.com/callback
  • 標準のアクセスタイプ : Read & Write (今回は書き込みするので)
  • ツイッターでログインする : チェックしない

Callback URLは http://localhost:3000/oauth_callback とか書くとエラーになるので、http://example.com/ のように適当なURLを記載しておきます。(実際にここで設定したURLがコールバックされるわけではありません)

だそうです。

Railsアプリを作る

OAuth認証Twitterアクセスを楽にするためのプラグインを入れてRailsアプリを作る。

sudo gem install oauth
sudo gem install twitter
rails _2.2.2_ twitpost
cd twitpost

処理の流れはこんな感じ。OAuthの流れについては自分が書くよりもhttp://tech.lampetty.net/tech/index.php/archives/323ゼロから学ぶOAuth:特集|gihyo.jp … 技術評論社にずっと読みやすい記事があるので割愛。

あとはざくざくとコードを書く。と言っても量は多くない。

コントローラindex作成

コントローラindexを作ってindex.htmlを削除。

./script/generate controller index index
rm public_html_index.html

config/routes.rb

map.root:controller=>'index'
map.connect':action', :controller=>'index'

app/views/index/index.html.erb

フォームはこれだけ。

<% form_tag(:controller=>:index, :action=>:tweet) do-%>
<%= text_area_tag "text" %>
<%= submit_tag "tweet" %>
<% end -%>

app/contollers/index_controller.rb

CONSUMER_KEY, CONSUMER_SECRETのところに最初に手に入れたコードを書く。

require 'oauth'
require 'twitter'

class IndexController < ApplicationController
  CONSUMER_KEY    = "*****"
  CONSUMER_SECRET = "*****"

  def self.consumer
    OAuth::Consumer.new(CONSUMER_KEY,
                        CONSUMER_SECRET,
                        {:site => "http://twitter.com"} )
  end

  def index
  end

  def authorized?
    return session[:oauth_token] && session[:oauth_token_secret]
  end

  def tweet
    session[:text] = params[:text]

    # 認証済みならセッションに記録された情報を元にツイートする
    if authorized?
      do_tweet
      redirect_to :action=>:index
      return
    end

    # 認証していないときは認証処理を始める
    request_token = IndexController.consumer.get_request_token(
      :oauth_callback=>"http://#{request.host_with_port}/oauth_callback"
    )
    session[:request_token]        = request_token.token
    session[:request_token_secret] = request_token.secret

    redirect_to request_token.authorize_url # twitter.comへリダイレクト

  end

  def oauth_callback
    consumer = IndexController.consumer

    request_token = OAuth::RequestToken.new(consumer,
                                            session[:request_token],
                                            session[:request_token_secret])

    access_token = request_token.get_access_token({},
                                                  :oauth_token    => params[:oauth_token],
                                                  :oauth_verifier => params[:oauth_verifier] )

    session[:oauth_token]        = access_token.token
    session[:oauth_token_secret] = access_token.secret

    do_tweet
    redirect_to :action=>:index
  end

  def do_tweet
    Twitter.configure do |config|
      config.consumer_key    = CONSUMER_KEY
      config.consumer_secret = CONSUMER_SECRET
      config.oauth_token        = session[:oauth_token]
      config.oauth_token_secret = session[:oauth_token_secret]
    end
   
    Twitter.update(session[:text]) if session[:text]
    session[:text] = nil
  end
end


大体こんな感じでtwitterに投稿できるWebアプリケーションが作れる。