image

  • フォト Amazonギフト券
    ※この時計の時刻は、閲覧しているパソコンのものであり、必ずしも正確な時間とは限りません

検索

最近のトラックバック

無料ブログはココログ

« ピックアップ:テレ東とTBSなぜ差がついたか, 紙製IBM ThnkPadを作ってみよう, etc... | トップページ | ピックアップ:IFRS2009 日本語訳を12月刊行, アジャイルは死んだのか, etc... »

2009-09-06

ruby (sinatra + haml) で twitter

ExtJS での twitter クライアント例を見つけた。
- http://www.extjs.com/forum/showthread.php?t=77234

> Ext.ux.myTwitter - Twitter Client - Ext JS Forums

shinatra を使った twitter クライアント例も。
- http://jasonbynum.com/2009/09/04/sinatra-twitter-and-httparty/
> Sinatra, Twitter, and HTTParty | Jason Bynum

これらは、通信部には php をつかっている。

これを参考にしつつ、
sinatra + haml + httparty
として、pure-ruby でサブセットを作ってみた。

20090906twitter
- http://homepage2.nifty.com/youichi_kato/src.html
> katoy 自作のソース
twitter アクセス (sinatra + haml + httparty) (2009-09-06)

ソース構成は次のとうり
$ tree .
.
|-- Views
|   |-- index.haml
|   `-- layout.haml
`-- twitter.rb
起動は $ ruby twitter.rb としてから、web ブラウザで http://localhost:4566 にアクセスするだけ。

以下にソースコードを示す。
$ cat twitter.rb
# See http://jasonbynum.com/2009/09/04/sinatra-twitter-and-httparty/

require 'rubygems'      # because we are need gems
require 'sinatra'       # because it's a sinatra app = DOH!
require 'httparty'      # because you like to party, and make dead simple, RESTful HTTP requests
require 'rack-flash'    # this is just handy if you want to pass flash messages to the views (optional)
require 'haml'
require 'time'
require 'uri'
require 'pp'

$KCODE="utf8"

use Rack::Flash     # use rack-flash (optional)
set :sessions, true # session have to be set to true in order to store flashes (optional)

# Very Basic Twitter class
class Twitter
  include HTTParty
  base_uri "twitter.com"
end

def pastetime(posttime)
  sec = (Time.new - Time.parse(posttime))
  return "#{sec.to_i} 秒" if sec < 60
  return "#{(sec/60).to_i} 分" if sec < 60 * 60
  return "#{(sec/(60*60)).to_i} 時間" if sec < 60 * 60  * 24
  return "#{(sec/(60 * 60 * 24)).to_i} 日"
end

# テキストデータ内のURL, @name をリンクにする
def url2link_of_string(html_string)

  URI.extract(html_string, ['http', 'https']).uniq.each{ |url|
    html_string.gsub!(url,"<a href='#{url}'>#{url}</a>")
  }

  s = html_string.clone
  s.scan(/@(\w*)/) {|x|
    html_string = html_string.gsub!("@#{x}", "@<a href='http://twitter.com/#{x}'>#{x}</a>")
  }
  html_string
end

post "/login" do
  if params[:user] != "" and params[:password] != ""
    session[:user] = params[:user]
    session[:password] = params[:password]
    session[:group] = 'friends'
  end
  redirect "/"
end

post "/logout" do
  session[:user] = nil
  session[:password] = nil
  session[:group] = 'public'
  redirect "/"
end

# Get our index page and display the lastest 12 tweets
get "/" do
  @group = session[:group]
  @group = params[:group] if params[:group] != nil
  @group = "public" if @group == nil
  session[:group] = @group
  Twitter.basic_auth(session[:user], session[:password])
  @tweets = Twitter.get("/statuses/#{@group}_timeline.json", :query => {:count => 20, :out => "json"})
  haml :index # use views/index.haml for view
end

#listen for a post on the index page
post "/" do
  # Post the tweet to Twitter
  Twitter.basic_auth(session[:user], session[:password])
  tweet = Twitter.post("/statuses/update.json", :query => { :status => params[:tweet]})
  flash[:notice] = "TWITTERD!" and redirect "/" if tweet.has_key?('id') # if it works
  flash[:notice] = "NOT TWITTERD :(" and redirect '/' # if it doesn't
end

$ cat layot.haml
!! Strict

%html
  %meta{ 'http-equiv' => 'content', :content => 'text/html; charset=utf-8'}
  %head
    %title Twitter With Sinatra
    %style{:type => "text/css", :media => "screen"}
      :plain
        blockquote#twitter {
          background: #e3e3e3;
          margin-top: -4px;
          margin-left: 4px;
          margin-right: 4px;
          margin-bottom: 0px;
        }
  %body
    %div{:id=>"wrapper"}
      %h2{:align=>"center"} Twitter With Sinatra
      != yield

$ cat index.haml
!! Strict

%html
  %meta{ 'http-equiv' => 'content', :content => 'text/html; charset=utf-8'}
  %head
    %title Twitter With Sinatra
    %style{:type => "text/css", :media => "screen"}
      :plain
        blockquote#twitter {
          background: #e3e3e3;
          margin-top: -4px;
          margin-left: 4px;
          margin-right: 4px;
          margin-bottom: 0px;
        }
  %body
    %div{:id=>"wrapper"}
      %h2{:align=>"center"} Twitter With Sinatra
      != yield
ntsitm234111:twitter2 youichikato$ cat Views/index.haml
- if flash[:notice]
  %div{:id=>"flash", :style=>"color:red;"}= flash[:notice]
%form{:action=>"/", :method=>"post"}
  %table
    %tr
      %td{:nowrap=>true}
        %textarea{:name=>"tweet", :rows=>"1", :cols=>"100"}
        %br
        %input{:type=>"submit", :value=>"Tweet this!", :disabled=> session[:user] == nil}

%center
  %table
    %tr
      %td{:nowrap=>true}
        %form{:action=>"/login", :method=>"post"}
          user:
          %input{:type=>"text", :name=>"user", :value=>session[:user]}
          password:
          %input{:type=>"password", :name=>"password", :value=>session[:password]}
          %input{:type=>"submit", :value=>"login"}
      %td{:nowrap=>true}
        %form{:action=>"/logout", :method=>"post"}
          %input{:type=>"submit", :value=>"logout", :disabled=> session[:user] == nil}
  %hr
  %form{:action=>"/", :method=>"get"}
    %input{:type=>"radio", :name=>"group", :value=>"public", :checked=> @group=='public'} public
    %input{:type=>"radio", :name=>"group", :value=>"friends", :checked=> @group=='friends'} friends
    %input{:type=>"radio", :name=>"group", :value=>"user", :checked=> @group=='user'} user
    %input{:type=>"submit", :value=>"Refresh"}

- if !@tweets.is_a?(Array)
  %h3 Sorry, something is wrong
  = @tweets.inspect
- else
  %ul
    - for tweet in @tweets
      %hr
      %li
        %img{:src=>"#{tweet['user']['profile_image_url']}", |
             :height=>"48", :width=> "48", :align=>"left", :alt=>"#{tweet['user']['name']}" }
          %a{:style=>"color: red;", :href=>"http://twitter.com/#{tweet['user']['screen_name']}"} #{tweet['user']['screen_name']}
          %small from #{tweet['source']}  #{pastetime(tweet['created_at'])}前
          %blockquote#twitter
            %span #{url2link_of_string(tweet['text'])}

twitter をプログラムから扱う基本は習得できたと思う。
EDINET や SEC 情報の変化を twitter で発信できるだろうと考えている。

« ピックアップ:テレ東とTBSなぜ差がついたか, 紙製IBM ThnkPadを作ってみよう, etc... | トップページ | ピックアップ:IFRS2009 日本語訳を12月刊行, アジャイルは死んだのか, etc... »

コメント

この記事へのコメントは終了しました。

トラックバック


この記事へのトラックバック一覧です: ruby (sinatra + haml) で twitter:

« ピックアップ:テレ東とTBSなぜ差がついたか, 紙製IBM ThnkPadを作ってみよう, etc... | トップページ | ピックアップ:IFRS2009 日本語訳を12月刊行, アジャイルは死んだのか, etc... »

mokuji

2013年12月
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        

google

  • twitter
  • __
  • _
    Googleボットチェッカー

合わせて読む

  • 合わせて読む
    フィードメーター - katoy: cocolog あわせて読みたい

リンク