sinatra+hamlを使ってTwitterクライアントライクなWebページを作成する
言語の仕様、vimのようなツールもさることながら、さっさと何かサービスをリリースしたいということもあったので、今回はフレームワークsinatraについて取り上げます。
環境設定
hamlをはじめて利用するので、gemをインストールします。
$ gem install haml
今回はshotgunで動作確認したので、shotgunもインストールしておきましょう。
$ gem install shotgun
viewの設定
views/index.haml
!!! XML !!! %html %head %meta{ :content=>"text/html", :charset=>"utf-8" } %title Post test %body #main %h1 Post test %div Let's tweet %form{:action=>"/", :method=>"post"} %input{:type=>"texfield",:name=>"str"} %input{:type=>"submit", :value=>"send"} %div= @message
テキストボックスに入力した言葉をPostするイメージです。
Postするアカウントは以前も利用した(https://twitter.com/#!/anime_stuffHis)になります。
設定の変更
学習記録③「heroku + sinatraでTwitterBOTを喋らせる」で利用したソースを少々変更し、WebページからPostできるよう設定します。
tweet.rb
require 'rubygems' require 'twitter_oauth' require 'twitter' class Tweet def tweet(str) t = TwitterOAuth::Client.new({ :consumer_key=>'任意の値を入力', :consumer_secret=>'任意の値を入力', :token=>'任意の値を入力', :secret=>'任意の値を入力' }) t.update "#{str}" end end
変更点は1つ。tweetメソッドに引数を持たせ、そのワードをポストするようにしました。
app.rb
require 'rubygems' require 'sinatra' require 'haml' require './tweet.rb' get '/' do 'under construction' haml :index end post '/' do Tweet.new.tweet(params[:str]) haml :index end
変更点は以下の通りです。
- require 'haml'を追加
- Tweetクラスのメソッドに引数を設定(詳細はtweet.rbの変更を参照)