Sinatra をインストールし,使ってみる

Sinatra をインストールし,使ってみる<。Sinatra のインストールは簡単です

In this Web pager, installing and using Sinatra is explained.

Sinatra をインストールし,使ってみる (Install Sinatra and try to use it)

◆ インストール (Install)

  1. ruby, rubygesm, sinatra のインストール (Install ruby, rubygems and sinatra)

    Ubuntu での実行手順例 (Instal Sinattra on Ubuntu)

    sudo apt -y update
    sudo apt -y install ruby
    sudo apt -y install ruby-dev
    sudo apt -y install rubygems
    sudo gem install sinatra
    
  2. erubis, eruby のインストール (Install erubis and eruby)
    sudo apt -y update
    sudo apt -y install erubis
    sudo apt -y install erubis-doc
    sudo apt -y install liberubis-ruby
    
    

◆ テスト実行 (try to use using a simple example)

* Classic スタイルの場合 (In case of "Classic Style" of Sinatra)

  1. ファイル hi.rb を作成 (edit hi.rb)
    require 'rubygems' 
    require 'sinatra'
    
    get '/hi' do
      erubis "Hello World!"
    end
    
  2. サーバの起動 (execute a server)
    ruby hi.rb
    

    Ubuntu での実行手順例 (In case of Ubuntu)

  3. Web ブラウザを使って開いてみる (Open a Web page using Web browser)

    http://localhost:4567/hi

* Moudlar スタイルの場合

  1. ファイル hi.rb を作成 (edit hi.rb)
    require 'rubygems'
    require 'sinatra/base'
    class MyApp < Sinatra::Base
      get '/hi' do
        erubis "Hello World!"
      end
    end
    MyApp.run! :host => 'localhost', :port => 4567
    
  2. 起動
    ruby hi.rb
    

    Ubuntu での実行手順例

  3. Web ブラウザを使って開いてみる

    http://localhost:4567/hi

◆ 試しに使ってみる (try to use)

  1. redis サーバの起動
    cd /tmp
    redis-server 
    
  2. ファイル hello.rb を作成 (edit hello.rb)
    require 'rubygems'
    require 'redis'
    require 'erubis'
    require 'sinatra/base'
    class MyApp < Sinatra::Base
      get '/hoge/new/key=:key&&field=:field&&value=:value' do
        @redis = Redis.new(:host => "127.0.0.1", :port => "6379", :db => "hoge")
        @redis.hset(params[:key], params[:field], params[:value])
      end
      get '/hoge/show' do
        @redis = Redis.new(:host => "127.0.0.1", :port => "6379", :db => "hoge")
        @keys = @redis.keys(glob = "*")
        erb :show
      end
      get '/hoge' do
        @redis = Redis.new(:host => "127.0.0.1", :port => "6379", :db => "hoge")
        @keys = @redis.keys(glob = "*")
        erb :show
      end
    end
    MyApp.run! :host => 'localhost', :port => 4568
    
  3. ファイル views/show.erubis を作成 (edit views/list.erubis)
    <HTML>
    <BODY>
    
    <table>
    <tr>
      <td width="150">key</td>
      <td width="150">field</td>
      <td width="150">value</td>
    </tr>
    
      <% @keys.each do |key| %>
      <%   @fields_and_values = @redis.hgetall(key) %>
      <%   @fields_and_values.each do |field_and_value| %>
    <tr>  
        <td><%= key %></td>
        <td><%= field_and_value[0] %></td>
        <td><%= field_and_value[1] %></td>
    </tr>
    <% end %>
    <% end %>
    </table>
    
  4. 起動
    ruby hello.rb
    

    Ubuntu での実行手順例

  5. Web ブラウザを使って開いてみる

    http://localhost:4568/hoge/new/key=T:2&&field=x&&value=101

    次に http://localhost:/hoge/show

Sinatra を使ってみる

ここで行うこと

ここで行うルーティングは下の通り。

REST URL without REST 処理
GET /hoge GET /hoge/show 「... => index」と表示
GET /hoge/new GET /hoge/new 「... => new」と表示
GET /hoge/[id]:edit GET /hoge/edit/[id] 「... => edit ...」と表示
GET /hoge/[id] GET /hoge/show/[id] 「... => show ...」と表示
DELETE /hoge/[id] GET /hoge/destroy/[id] 「... => destroy ...」と表示
PUT /hoge/[id] POST /hoge/update/[id] 「... => update ...」と表示
POST /hoge POST /hoge/create 「... => create ...」と表示

◆ ルーティング(テンプレート無し,レイアウト無し)の例

  1. 次のファイルを作り、hi.rb のようなファイル名で保存する (edit "hi.rb")

    HTML エスケープのためのメソッドとして hを定義している。

    require 'rubygems'
    require 'sinatra/base'
    require 'erubis'
    
    class MyApp < Sinatra::Base
      helpers do
        # define method "h" to escape HTML                                       
        include Rack::Utils; alias_method :h, :escape_html
      end
      get '/hoge' do
        erubis h "GET <</hoge>>       => index"
      end
      get '/hoge/show' do
        erubis h "GET <</hoge/show>>  => index"
      end
      get '/hoge/new' do
        erubis h "GET <</hoge/new>>   => new"
      end
      get %r{^/hoge/([0-9]+):edit$} do
        erubis h "GET <</hoge/#{params[:captures]}>>         => edit #{h params}"
      end
      get %r{^/hoge/edit/([0-9]+)$} do
        erubis h "GET <</hoge/edit/#{params[:captures]}>>    => edit #{h params}"
      end
      get %r{^/hoge/([0-9]+)$} do
        erubis h "GET <</hoge/#{params[:captures]}>>         => show #{h params}"
      end
      get %r{^/hoge/show/([0-9]+)$} do
        erubis h "GET <</hoge/show/#{params[:captures]}>>    => show #{h params}"
      end
      delete %r{^/hoge/([0-9]+)$} do
        erubis h "DELETE <</hoge/#{params[:captures]}>>      => destroy #{h params}"
      end
      get %r{^/hoge/destroy/([0-9]+)$} do
        erubis h "GET <</hoge/destroy/#{params[:captures]}>> => destroy #{h params}"
      end
      put %r{^/hoge/([0-9]+)$} do
        erubis h "PUT <</hoge/#{params[:captures]}>>        => update #{h params}"
      end
      post %r{^/hoge/update/([0-9]+)$} do
        erubis h "POST <</hoge/updte/#{params[:captures]}>> => update #{h params}"
      end
      post '/hoge' do
        erubis h "POST <</hoge>>                            => create #{h params}"
      end
      post '/hoge/create' do
        erubis h "POST <</hoge/create>>                     => create #{h params}"
      end
    end
    MyApp.run! :host => 'localhost', :port => 4567
    

    Sinatra でのルーティングの要点

    • Sinatra では get, post, put, delete メソッドがある.
    • get, post, put, delete メソッドのあとにルートのパターンを書く
    • get, post, put, delete メソッドを複数書いた場合には、先頭から順に評価される。マッチするものがあればルーティングが行われ、それ以降は評価されない。
    • ルートのパターンに、 正規表現を含めることができる

      例:「%r{^/hoge/([0-9]+):edit$}」

      「^」が行頭,「$」が行末(これらを省略した場合には、任意の部分文字列にマッチングする)

    • ルートのパターンに、名前付きパラメータを含めることができる

      例:「/hoge/:act

      名前はなんでも良い。ここでは名前は「act」。 名前付きパラメータで取得した値は 「#{params[:path]}」のようにして,簡単に得ることができる.

    • ルートのパターンに、「*」を含めることができる
      • get '/hoge/:path' は,/hoge/a にはマッチするが /hoge/a/b や /hoge/a/b/c にはマッチしない
      • get '/hoge/*' は,/hoge/a にも /hoge/a/b にも /hoge/a/b/c にもマッチ
    • URL 内のパラメータの取得

      URL 内のパラメータ(例えば「?a=100」のようなもの)は, params[:a]で取得できる

  2. 起動
    ruby hi.rb
    
  3. Web ブラウザを使って開いてみる

    下のように 「<</hoge/show/123>>:」のように表示される(たしかにHTML エスケープが行われている

      http://localhost:4567/hoge/show
    • http://localhost:4567/hoge/new
    • http://localhost:4567/hoge/edit/123
    • http://localhost:4567/hoge/show/123
    • http://localhost:4567/hoge/destroy/123

◆ ルーティング(テンプレート有り,レイアウト無し)の例

  1. 次のファイルを作り、hi.rb のようなファイル名で保存する (edit "hi.rb")

    , :locals => {:id => "#{params[:captures]}" }」 の部分は,erubis ファイルの中で使いたいローカル変数の設定を行っている.

    require 'rubygems'
    require 'sinatra/base'
    require 'erubis'
    
    class MyApp < Sinatra::Base
      helpers do
        # define method "h" to escape HTML                                       \
                                                                                  
        include Rack::Utils; alias_method :h, :escape_html
      end
      
      get %r{^/hoge/show/([0-9]+)$} do
        erubis :show, {:id => "#{params[:captures]}" }
      end
    end
    MyApp.run! :host => 'localhost', :port => 4567
    
  2. views/show.erubis ファイルの作成

    Sinatra の流儀では、 テンプレート・ファイルは,デフォルトでは,/views ディレクトリ下に置くことになっている。

    テンプレート・ファイルのファイル名には、拡張子「.erubis」を忘れないこと。

    <HTML>
    <BODY>
    <p>
    id = <%= h id %>
    </BODY>
    </HTML>
    
  3. 起動
    ruby hi.rb
    
  4. Web ブラウザから使ってみる

    http://localhost:4567/hoge/show/123

    下のように /views/show.erubis の評価結果が、 「id = 123」のように表示される

◆ erubis ファイルの中で Ruby のメソッド呼び出し

〜.erubis ファイルの中で,他の Ruby ファイルを取り込みたい. これは,Ruby ファイルで,クラスや関数を定義しておいて, 〜.erubis ファイルの中で使いたいということです.

  1. 先ほどの「erubis ファイルをビューファイルとして使う」での hi.rb をそのまま使う (use the previout "hi.rb")
  2. hoge.rb の例 (edit views/hoge.rb)
    def f(n)
      2 * n
    end
    
  3. views/show.erubis ファイルの作成

    Sinatra の流儀では、 テンプレート・ファイルは,デフォルトでは,/views ディレクトリ下に置くことになっている。

    拡張子「.erubis」を忘れないこと。

    <HTML>
    <BODY>
    <p>
    <% require 'views/hoge.rb' %>
    <p>
    id = <%= h id %>
    <p>
    f id = <%= f id.to_i %>
    </BODY>
    </HTML>
    
  4. Web ブラウザから使ってみる

    http://localhost:4567/hoge/show/123

    下のように /views/show.erubis の評価結果が 表示される。「f 123 = 246」の部分は、Ruby のメソッドの評価結果を表示している。 これは、erubis ファイルでは「f id = <%= f id.to_i %>」の部分である。

◆ erubis ファイルの中で JavaScript を使ってみる。

「erubis ファイル」と言っているのは、HTML の中に erubis のプログラムが埋め込まれたようなものであった。 HTML なので JavaScript を使うことも問題なく行える(Sinatra の側で何かの設定を行うようなことはない)。 念のため試してみる。

  1. 先ほどの「erubis ファイルをビューファイルとして使う」での hi.rb をそのまま使う (use the previout "hi.rb")
  2. views/show.erubis ファイルの作成

    Sinatra の流儀では、 テンプレート・ファイルは,デフォルトでは,/views ディレクトリ下に置くことになっている。

    拡張子「.erubis」を忘れないこと。

    <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
      <head>
        <meta http-equiv="Content-Type" content="text/html; initial-scale=1.0; charset=utf-8" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="MSThemeCompatible" CONTENT="yes" />
    
        <title>Google Maps API sample</title>
    
        <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
          <!--
           google.maps.event.addDomListener(window, 'load', function() {
           var latlng = new google.maps.LatLng(33.104053, 131.78092); 
           var myOptions = {
           zoom: 12,
           center: latlng,
           mapTypeId: google.maps.MapTypeId.ROADMAP,
           scaleControl: true,
           };
           var map = new google.maps.Map(document.getElementById("googlemap"), myOptions);
           });
           // -->
          </script>
        </head>
    
        <body style="width : 500px; height : 400px;">
          <p> 
            id = <%= h id %>
          <p> 
            <div id="googlemap" style="width : 400px; height : 300px;"></div> 
        </body>
    </html>
    
    
  3. Web ブラウザから使ってみる

    http://localhost:4567/hoge/show/123

    下のように /views/show.erubis の評価結果が 表示される。

◆ erubis ファイルの中で JavaScript を使ってみる。

「erubis ファイル」と言っているのは、HTML の中に erubis のプログラムが埋め込まれたようなものであった。 HTML なので JavaScript を使うことも問題なく行える(Sinatra の側で何かの設定を行うようなことはない)。 念のため試してみる。

  1. 次のファイルを作り、hi.rb のようなファイル名で保存する (edit "hi.rb")
    require 'rubygems'
    require 'sinatra/base'
    require 'erubis'
    
    class MyApp < Sinatra::Base
      helpers do
        # define method "h" to escape HTML                                       \
                                                                                  
        include Rack::Utils; alias_method :h, :escape_html
      end
      
      get '/hoge/show' do
        erb :show
      end
      get '/hoge/new' do
        erb :new
      end
      post '/hoge/create' do
        erb :create, :locals ='> {:params ='> params }
      end
    end
    MyApp.run! :host ='> 'localhost', :port ='> 4567
    
  2. views/show.erubis ファイルの作成
    <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
      <head>
        <title>show</title>
        </head>
    
        <body>
          <% require 'rubygems' %>
          <% require 'sqlite3' %>
          <% db = SQLite 3::Database.new("/home/windowslike/views/mydb") %>
          <% a = db.execute("SELECT * FROM persons;") %>
          <% db.close() %>
          <%= a %>
        </body>
    </html>
    
  3. views/new.erubis ファイルの作成
    <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
      <head>
        <title>new</title>
        </head>
    
        <body>
        <p>Please input your name</p>
        <form action='/hoge/create' method='POST'>
          <p>
          name: 
          <input type='text' name='name'>
          <p>
          commente: 
          <input type='text' name='comment'>
          <p>
          <input type='submit' value='Send'>
        </form>
    
        </body>
    </html>
    
  4. views/create.erubis ファイルの作成
    <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
      <head>
        <title>create</title>
        </head>
    
        <body>
          <p> 
            name = <%= params[:name] %>
          <p> 
            comment = <%= h params[:comment] %>
    
          <% require 'rubygems' %>
          <% require 'sqlite3' %>
          <% db = SQLite 3::Database.new("/home/windowslike/views/mydb") %>
          <% db.execute("insert into persons values ( '#{params[:name]}', '#{params[:comment]}' )") %>
          <% db.close() %>
        </body>
    </html>
    
  5. 起動
    ruby hi.rb
    
  6. Web ブラウザから使ってみる

    http://localhost:4567/hoge/new