1.2.3のころRailsを仕事で少し使ってたのですが、BPStudy#30の予習のため最近のRailsどうなってるかな、と再入門中。いろいろメモ。
rvm/ruby1.8.7/rails2.3.5の環境でやる。
結構忘れてる。手元にRuby/Rails関連の入門書がないのでドキュメントとかソース読みながらやる。今の自分ならそれでなんとかなる・・・はず。
とりあえずプロジェクト作って動かす
$ rails myproject $ cd myproject $ script/server
で、0.0.0.0:3000でWEBrickのHTTPサーバが起動する。が、"About this app’s environment"のリンクをクリックすると500エラーが出た。
ログを見るとsqlite3のモジュールが入ってないとな。
aptでlibsqlite3-devパッケージをインストールしてから、sqlite3-rubyをgemでインストールした。
$ sudo apt-get install libsqlite3-dev $ gem install sqlite3-ruby
これで環境の表示がうまく動いた。
Hello worldを表示する
さて、雛形のテンプレートが表示されてもあんまり嬉しくはないので、Hello worldを表示することにする。
controllerを作る
$ script/generate controller hello
これで myproject/app/controllers/hello_controller.rb が作成される。ほかにもいくつか関連するファイルが作られるけど、放置。
hello_controller.rbを編集する
HelloControllerクラスにテキストで "Hello, world!" というレスポンスを返すアクション(メソッド)を定義する。
class HelloController < ApplicationController def index render :text => 'Hello, world!' end end
デフォルトアクセスだとindexが使われるんだったかな。
これでscript/serverを実行して、 /hello や /hello/index/ などでアクセスすると "Hello, world!" と表示される。
サイトのルートで表示させる
やっぱり、 /hello じゃなくて / で表示させたいのでURLのルーティングを今度は編集する。
myproject/config/routes.rb を見てみる。コメントは重要なもの以外無視。
ActionController::Routing::Routes.draw do |map| # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end
デフォルトだと、"コントローラ名/アクション名/ID" のようなアクセスが有効になっている。これを外してサイトトップではHello worldを表示させる。
コメントに map.root で指定するといいよ、ってあるのでその通りに routes.rb を編集する。
ActionController::Routing::Routes.draw do |map| # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" #map.connect ':controller/:action/:id' #map.connect ':controller/:action/:id.:format' map.root :controller => "hello" end
myproject/public/index.html を消さないとそちらが優先で表示されてしまうので、ファイルを削除する。
$ rm myproject/public/index.html
サイトルートの / にアクセスすると "Hello, world!" と表示された。
次はunittestとか試してみたいな。spec使うほうがいいのだろうか?