金子邦彦研究室プログラミングRuby による Web/データベース・プログラミングWEBrickサーバで eRuby を動かしてみる

WEBrickサーバで eRuby を動かしてみる

Web ブラウザで,eRuby が埋め込まれた HTML ファイルを開くと,何かの「動く」Web ページが表示される. これを行ないたい. この目的では apache は使いづらい(ように感じる)ので,WEBrickサーバを使う

erb ファイルを実行してみる

【ここで行うこと】

  1. WEBrick サーバを起動する Ruby プログラム

    ファイル名:webserver.rb

    #! ruby -Ku
    # -*- coding: utf-8 -*-
    require "webrick"
    config = {
        :Port => 8099,
        :DocumentRoot => '.'
    }
    
    WEBrick::HTTPServlet::FileHandler.add_handler("erb", WEBrick::HTTPServlet::ERBHandler)
    s = WEBrick::HTTPServer.new(config)
    s.config[:MimeTypes]["erb"] = "text/html"
    
    trap(:INT){
        s.shutdown
    }
    s.start
    
  2. WEBrick サーバを起動する Ruby プログラム」の実行

    [image]
  3. Web ブラウザで開く

    Web ブラウザで, http://localhost:8099 を開く

  4. 結果の確認

    ファイルの一覧が表示される(普通の Web サーバと同じ振る舞い).

    ※ 先程のプログラム webserver.rb を,C:/Ruby/programs/webというディレクトリに置いている場合には,そのディレクトリ内のファイルの一覧が表示される.

    [image]
  5. erb プログラムの見本

    ◇ hello.erb

    <%= "Hello, World!!" %>
    

    ■ 実行結果の例

    [image]

    ◇ sample1.erb

    <%
     a = 1
     b = 2
     c = 3
    %>
    
    A = <%= a %><br />
    B = <%= b %><br />
    C = <%= c %>
    

    ■ 実行結果の例

    [image]

    ◇ sample2.erb

    <% 10.times do |i| %>
    <% a = rand(10) %>
    <% b = rand(10) %>
    (<%= i+1 %>) <%= a %> + <%= b %> = <%= a + b %><br />
    <% end %>
    

    ■ 実行結果の例

    [image]

フォームを使ってみる

  1. WEBrick サーバを起動する Ruby プログラム

    ファイル名:webserver.rb

    #! ruby -Ku
    # -*- coding: utf-8 -*-
    require "rubygems"
    require "webrick"
    require "erb"
    config = {
        :Port => 8099,
        :DocumentRoot => '.'
    }
    
    WEBrick::HTTPServlet::FileHandler.add_handler("erb", WEBrick::HTTPServlet::ERBHandler)
    s = WEBrick::HTTPServer.new(config)
    s.config[:MimeTypes]["erb"] = "text/html"
    s.mount_proc("/hello2") { |req, res| 
      p req.query 
      name = req.query["name"]
      template = ERB.new( File.read('hello2.erb') )
      res.body << template.result( binding )
    }
    trap(:INT){
        s.shutdown
    }
    s.start
    
  2. submit.html

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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>
                Sample
            </title>
        
        </head>
    
        <body>
                
            <form action="hello2" method='post'>
            <input type='text' name='name' size=10/>
            <br/>
            <input type='submit' name='submit' value='submit'/>
            </form> 
              
        </body>
    </html>
    
  3. hello2.erb

    <?xml version="1.0" encoding="UTF-8"?>
    <% # coding: UTF-8 %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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>
                Sample
            </title>
        
        </head>
    
        <body>
                
            hello, <%= name %>
              
        </body>
    </html>
    
  4. WEBrick サーバを起動する Ruby プログラム」の実行

    [image]
  5. Web ブラウザで開く

    Web ブラウザで, http://localhost:8099/submit.html を開く

    [image]

    [image]
  6. 結果の確認

    [image]

Ruby on Rails バージョン 3 で実行してみる(書きかけ)

Ruby on Railsのアプリケーション内のビューファイルとしてerbファイルを実行する方法.

[image]

C:/Ruby/railsproject/hello2に移動して、WEBrickサーバを起動.

【Rails3 での注意点】 WEBrickサーバの起動には「ruby script/server」というコマンドを使っていたが、Rsils3では「rails server」または「rails s」 に変更されている.

  • http://localhost:3000/main/hello
  • http://localhost:3000/main/sample1
  • http://localhost:3000/main/sample2

    [image]

    最初に「http://localhost:3000/main/hello」を入力して実行しようとしたところ、Routing Errorというエラーが起きた.

    原因は、アプリケーションを作成した際にできる、/アプリケーション名/config/routes.rbというファイルの内容が全てコメントアウトされていたため.

    「match ':controller(/:action(/:id(.:format)))'」という記述のコメントアウトをはずすことで解決.