Dojo + Rails で"Hello World" その2

makotoi2007-06-13


前回はDojo Wiki の例題を題材Rails上でdojoを使って"hello world!!"ボタンを押すと"You pressed the button"というアラートボックスを出す方法を試してみました。djconfigという変数にdojoのおいてあるpathを指定した以外はDojo Wikiの例題そのままです。 この例題を読み進めていくと、サーバーにリクエストを送ってその返り値をダイナミックに表示する方法がASP, PHP, JSP, Perl, Cold Fusionでは載っていたのですがRails用が載っていなかったので、自分で適当に作ってみました。そのメモです。

今回はリクエストを送るサーバのURLが重要になってくるので、Rails のプロジェクト作るところから始めます。

1. プロジェクト作成


$ rails HelloWorldOnRails
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments


2. コントローラ作成


$ cd hello_world_on_rails/
$ script/generate controller Hello index response_get response_post
exists app/controllers/
exists app/helpers/
create app/views/hello
exists test/functional/
create app/controllers/hello_controller.rb
create test/functional/hello_controller_test.rb
create app/helpers/hello_helper.rb
create app/views/hello/index.rhtml
create app/views/hello/response_get.rhtml
create app/views/hello/response_post.rhtml

3. dojoのライブラリーを public/javascript/dojoにダウンロード

4. 空のデータベースを作った後にウェッブサーバを立ち上げ


$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 5.0.27-max

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> create database hello_world_on_rails_development
-> ;
Query OK, 1 row affected (0.13 sec)

mysql> create database hello_world_on_rails_test;
Query OK, 1 row affected (0.00 sec)

$ script/server
=> Booting Mongrel (use 'script/server webrick' to force WEBrick)
=> Rails application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server

Starting Mongrel listening at 0.0.0.0:3000

Starting Rails with development environment...


5. index.rhtmlに以下の文を挿入




<%= controller.action_name %>




Please enter your name:


URLを指定するときにerbでURLを自動生成した以外はDojo Wiki のサンプルをほぼそのまま適用可でした。

url:"<%= url_for :controller => "hello", :action => "response_get" %>",


6. response_get.rhtmlに以下を追加

Hello <%= @name %> , welcome to the world of Dojo!

7. hello_controller.rbにフォームから送られてきたnameパラメターを変数に代入


class HelloController < ApplicationController

def index
end

def response_get
@name = params[:name]
end

def response_post
end
end

以上でテキストボックスに何か記入してボタンを押すと "Hello $name, Welcome to the world of Dojo!"。というボップアップが出てくるはずです($nameのところがテキストボックスに入れた値になっているはず)。