2009年07月11日

【1日1Rails】script/generate その2

コントローラの自動生成
script/generate controller [action]


script/generate controller

# コントローラを作成する
$ script/generate controller test_ctrl
      # このコントローラに対応するviewを置くディレクトリ
      create  app/views/test_ctrl
      # コントローラ本体(リクエストに応じて処理を受け付けるところ)
      # 中身はApplicationControllerを継承したクラスがいるだけ
      create  app/controllers/test_ctrl_controller.rb
      # テスト用モジュール
      # 雛形として必ずtrueになるAssertが1ついる
      create  test/functional/test_ctrl_controller_test.rb
      # 空のヘルパー(ERBから呼び出せるヤツ)暮らす
      create  app/helpers/test_ctrl_helper.rb
      # 空のヘルパー用テストモジュール
      create  test/unit/helpers/test_ctrl_helper_test.rb

# 上記の例ではコントローラのみ作成したが、引数を付けると
# アクションもまとめて生成できる
# とりあえず、indexというアクションを作ってみる
# -fを付けて、前の出力分を上書き
$ script/generate controller test_ctrl index -f
   # コントローラを上書きした
   # 中を見ると、indexというメソッドが出来ている
       force  app/controllers/test_ctrl_controller.rb
   # identical は同一だから何もしないよという意味
   identical  test/functional/test_ctrl_controller_test.rb
   identical  app/helpers/test_ctrl_helper.rb
   identical  test/unit/helpers/test_ctrl_helper_test.rb
   # viewを勝手に作ってくれる
      create  app/views/test_ctrl/index.html.erb

# この状態でサーバ立ち上げれば、一応、index.html.erbの結果が見れる
$ script/server

# ここにアクセス
http://localhost:3000/test_ctrl


# あと、-hでcontrolerのヘルプが見れる
$ script/generate controller -h