再度Railsでtwitterサービスに挑戦

前回までで、
KRAY - みんなで考え、作り、価値を生み出す
という素晴らしい記事を参考にして超簡単なtwitterサービス(1文をポストするだけ)をつくったわけだが、本質的にまだまだ理解していない部分があるので再度つくってみる。

今度、参考にさせていただく記事はこちら
http://mitukiii.jp/2011/01/16/rails3-create-twitter-mashup-application/

プロジェクトを作成して、Gemを管理するためにGemFileにいくつか書き加える。
Gemfileの書き方について参考にさせていただいたのは以下の記事。
bundlerのREADMEを読んでのメモ - おもしろwebサービス開発日記

gem 'rubytter'
group :development, :test do
gem 'rspec-rails', '>= 2.3.0'
end

gem 'rubytter'
#rubytterのライブラリをひっぱってくるということ。
group :development :test do
#groupは、プラグインを使いたいenvironmentsを設定するものらしい。

んで、bundle installを実行。

$ bundle install
Fetching source index for http://rubygems.org/
Using rake (0.8.7)
Using abstract (1.0.0)
Using activesupport (3.0.6)
Using builder (2.1.2)
Using i18n (0.5.0)
Using activemodel (3.0.6)
Using erubis (2.6.6)
Using rack (1.2.2)

次にコントローラとルーティングを作成する。

$ rails generate controller index index oauth callback
create app/controllers/index_controller.rb
route get "index/callback"
route get "index/oauth"
route get "index/index"
invoke erb
create app/views/index
create app/views/index/index.html.erb
create app/views/index/oauth.html.erb
create app/views/index/callback.html.erb
invoke rspec
create spec/controllers/index_controller_spec.rb
create spec/views/index
create spec/views/index/index.html.erb_spec.rb
create spec/views/index/oauth.html.erb_spec.rb
create spec/views/index/callback.html.erb_spec.rb
invoke helper
create app/helpers/index_helper.rb
invoke rspec
create spec/helpers/index_helper_spec.rb

rails generate controller index index oauth callback
は、indexというコントローラと、index,oauth,callbackの3つのアクションを追加するということ。
rails g controller index index oauth callbackでもよいとのこと。
各アクションに関して、indexは認証ボタンの表示/ツイートの表示、oauthは認証ボタンを押した時にTwitterに転送、callbackはTwitterから認証された時の後処理、に使用する。

また、
rails g controller Aで、Aというコントローラ作成、
rails g model Bで、Bというモデル作成、
rails g migration Cで、Cというマイグレーションを作成する。

MVCモデルに関してはこちら。
まつもと直伝 プログラミングのオキテ 第20回 MVCとRuby on Rails | 日経 xTECH(クロステック)

次は、config/routes.rbの書き換え。

get "index/index"
get "index/oauth"
get "index/callback"

を以下のように書き換え。

root to: "index#index", as: :index
get "/oauth" => "index#oauth", as: :oauth
get "/callback" => "index#callback", as: :callback

これで、サーバをrails serverコマンド で起動。が、しかし、エラーで起動しない。。。
なるほど。routes.rbを正しくかかないと起動せんのだな。とりあえず、以下に修正して起動はできた。

root :to => "index#index"
get "oauth" => "index#oauth"
get "callback" => "index#callback"

で、app/views/index/index.html.erbを

<% form_tag :oauth, method: :get do |f| %>
<%= submit_tag '認証する' %><% end %>

に変えて、localhost:3000にアクセスすると・・・コンパイルエラー。。。SyntaxError in Index#indexとのこと。

index.html.erb:1: syntax error, unexpected ':', expecting kEND
...ing= form_tag :oauth, method: :get do |f|
^

なので以下に変更。

<% form_tag(:oauth, {:method => :get }) do |f| %>
<%= submit_tag 'apply' %><% end %>

コンパイルできたので、localhost:3000にアクセス。
以下の画面が表示された。(ボタンのみ)

んで、例のtwitterのアプリを登録してConsumer KeyとConsumer Secretを取得して、それらを、app/controllers/application_controller.rbに書き出す。(記事通り)