Ruby on Rails 3 アプリケーションプログラミング(2/9)
Ruby on Railsの基本
railsコマンド(アプリケーションの作成) |
---|
rails new アプリケーション名 [オプション] |
オプション(使いそうなもの抜粋)
オプション | 内容 |
---|---|
-d、--database=DATABASE | 初期設定のDBMS(mysql , oracle , postgresql , sqlite3 , frontbase , ibm_db から選択) 指定しなければ sqlite3 |
--skip-gemfile | GEMfileを作成しない |
-O、--skip-active-record | Actibe Recordを組み込まない |
-T、--skip-test-unit | Test::Unitを組み込まない |
-J、--skip-prototype | prototype.jsを組み込まない |
-f、--force | ファイルが存在すれば上書き |
-s、--skip | すでに存在するファイルはスキップ |
-q、--quiet | 進捗状況を表示しない |
いっぱいディレクトリが作られる。
よく使うのは /app /public /script の3つ
/app ... 開発したコードを保管
/public ... HTTP経由で公開するディレクトリ。静的ファイルを格納。
/script ... サーバの起動・コード生成等のヘルパ。削除してはいけない。
この状態でWEBrickサーバを上げればRailsの初期ページが見れる。
$ rails new railsApp
$ cd railsApp
$ rails s
コントローラの基本
Rails開発の基点。ビジネスロジック(Model)の呼び出し、結果出力(View)への引渡しを実装。
コントローラクラスとはリクエストの受信からレスポンスの送信まで一手に担う。
rails generateコマンド(コントローラクラスの生成) |
---|
rails g controller コントローラ名[オプション] |
g は generate の略 |
使いそうなオプション
オプション | 内容 |
---|---|
-f、--force | ファイルが存在すれば上書き |
-s、--skip | すでに存在するファイルはスキップ |
-q、--quiet | 進捗状況を表示しない |
-e、--template-engine=NAME | 使用するテンプレートエンジン(デフォルトは erb) |
-t、--test-framework | 使用するテストフレームワーク(デフォルトは test_unit) |
--helper | ヘルパの生成有無(デフォルトは true) |
$ rails g controller helloWorld create app/controllers/hello_world_controller.rb invoke erb create app/views/hello_world invoke test_unit create test/functional/hello_world_controller_test.rb invoke helper create app/helpers/hello_world_helper.rb invoke test_unit create test/unit/helpers/hello_world_helper_test.rb invoke assets invoke coffee create app/assets/javascripts/hello_world.js.coffee invoke scss create app/assets/stylesheets/hello_world.css.scss
View をディレクトリまで自動作成。
作成するコントローラに実装するView名が決まっている場合は、以下のようにすれば、Helloコントローラに show アクションを作り、 show.html.erb まで作成できる。
$ rails g controller helloWorld show -f force app/controllers/hello_world_controller.rb route get "hello_world/show" invoke erb exist app/views/hello_world create app/views/hello_world/show.html.erb invoke test_unit force test/functional/hello_world_controller_test.rb invoke helper identical app/helpers/hello_world_helper.rb invoke test_unit identical test/unit/helpers/hello_world_helper_test.rb invoke assets invoke coffee identical app/assets/javascripts/hello_world.js.coffee invoke scss identical app/assets/stylesheets/hello_world.css.scss
作成されたコントローラを修正し、HTTPアクセスできることを確認。
- app/controllers/hello_world_controller.rb
- 修正前
class HelloWorldController < ApplicationController def show end end
-
- 修正後
# codig: utf-8 class HelloWorldController < ApplicationController def show render :text => 'hello, World!' end end
これでいきなりサーバを立ちあげてアクセスしたいところだが、標準の設定ファイルではルーティングが通ってない。config/routes.rb の以下の行をコメントインする必要がある。
match ':controller(/:action(/:id))(.:format)'
以下のようにリクエストURLにマッチする。
http://localhost:3000/controller
http://localhost:3000/controller/action
http://localhost:3000/controller/action/id
http://localhost:3000/controller/action/id.format
シロウトにはコメントアウトされていることが心外なくらい有用な定義であるが、This is a legacy wild controller route that's not recommended for RESTful applications. で Rails の思想とは異なる様子。こまけぇことは気にしない。
Webサーバを立ち上げれば以下のURLでアクセスできる。
コントローラの命名規則
種類 | 概要 | 例 |
---|---|---|
クラス名 | 先頭は大文字、接尾語に[Controller] | HelloController |
クラスファイル名 | クラス名を小文字にし、アンダースコア区切り | hello_controller.rb |
ヘルパファイル名 | コントローラ名に接尾語 [_helper.rb] | hello_helper.rb |
テストスクリプト名 | コントローラ名に接尾語 [_controller_test.rb] | hello_controller_test.rb |
ビューの基本
ERB = Embedded Ruby
- 任意のRubyスクリプトが埋め込める。条件分岐、繰り返し構文等
- ビューヘルパを使えばDBから取得した値に基づいたリンクやフォーム要素等をシンプルに実装可
ビュークラスには genetate コマンドがないので手書き。コントローラのgenerate時にアクション名まで指定すれば アクション名.html.erb ファイルを生成してくれる。
デフォルトで呼び出されるViewのファイル名は「app/views/コントローラ名/アクション名.html.erb 」。
アクションが存在しない場合はビューファイルを直接表示してくれる。ただし、コントローラクラスが存在しなければ表示できない。
- ex ) app/views/hello/nothing.html.erb →◎http://localhost:3000/hello/nothing
- ex ) app/views/noClass/nothing.html.erb →☓
- コントローラクラスのアクションメソッド(.rbファイル)
- app/controllers/hello_controller.rb
class HelloController < ApplicationController def view @msg = '世界' end
- テンプレート(.html.erbファイル)
- app/views/hello/view.html.erb
<div id="main"> <%= @msg %> </div>
任意の呼び出しをしたければコントローラに
render 'ctrl/ninnino_view_name'
を記述すれば「ninnino_view_name.html.erb 」を使える。
コメント構文
-
- 変数展開はされないが、ブラウザから見えるコメント。
- <%# 〜コメント(1行コメントと見せかけて改行も可)〜 %>
- <% if false %>〜コメント〜<% end %>
- =begin 〜コメント〜 =end
例)
<% =begin ここはコメントブロックです。 <% msg = 中に何かあっても無視されます。 %> <%= '出力しません' %> =end %>
モデルの基本
Railsが標準でサポートする ActiveRecord O/R(Object/Relational)マッパは、インピーダンスミスマッチを解消するツールとして有用。ActiveRecord では1テーブルを1モデルクラスとして表現する。
- データベース接続の設定
- config/database.yml
development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000
- adapter : 接続するDBMS (sqlite3, mysql, postgresql)
- database : データベース名
- host : ホスト名 / IP
- port : ポート番号
- pool : 接続プール
- timeout : タイムアウトミリ秒
- encoding : 文字コード
- username : ユーザ名
- password : パスワード
- socket : ソケット (/tmp/mysql.sock など)
- モデルクラスの作成
rails generateコマンド(モデルクラスの生成) |
---|
rails g model モデル名 [フィールド名]:[データ型] [...] [オプション] |
例)
$ rails g model user id:integer email:string password:string
- データ型について
マイグレーション | SQLite | Ruby | |
---|---|---|---|
integer | INTEGER | Fixnum | |
decimal | DECIMAL | BigDecimal | |
float | Float | Float | |
string | VARCHAR(255) | String | |
text | TEXT | String | |
binary | BLOB | String | |
date | DATE | Date | |
datetime | DATETIME | Time | |
timestamp | DATETME | Time | |
time | TIME | Time | |
boolean | BOOLEAN | TrueClass / FalseClass |
- オプションについて
オプション | 概要 | 初期値 |
---|---|---|
-o、--orm=NAME | 使用するO/Rマッパ | active_record |
--migration | マイグレーションファイルの生成有無 | true |
--timestamps | 作成日・更新日のタイムスタンプ列の自動生成有無 | true |
-t、--test-framework=NAME | 使用するテストフレームワーク | test_unit |
--fixture | フィクスチャ(テストデータを流し込む仕組み)使用有無 | true |
- モデル関連の命名規則
種類 | 概要 | 名前 |
---|---|---|
クラス | 先頭大文字単数形 | Book |
クラスファイル | 先頭小文字単数形 | book.rb |
テーブル | 小文字複数形 | books |
テストスクリプト | 先頭小文字単数形 | book_test.rb |
- マイグレーションファイルによるテーブル作成
- rake db:migrate
- db/migrate/* 配下から実行すべきファイルを自動判断してくれる。
- フィクスチャによるデータ流し込み
- rake db:fixtures:load FIXTURES=テーブル名
- test/fixtures/テーブル名.yml ファイルを探してくれる。
- データベースクライアントの起動
$ rails dbconsole > .tables schema_migrations users > .schema users CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar(255), "password" varchar(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
- HTTPサーバ起動時の接続先について
railsコマンド(HTTPサーバの起動) |
---|
rails s HTTPサーバ名 [オプション] |
s ... serverの略 |
- よく使うオプション
オプション | 内容 | 初期値 |
---|---|---|
-p、--port=PORT | ポート番号 | 3000 |
-b、--binding=IP | バインドするIPアドレス | 0.0.0.0 |
-d、--daemon | デーモンとして起動 | false |
-e、--environment=NAME | NAMEで指定した環境(test、development、production etc)で立ちあげ | development |
-P、-pid=FILEPATH | PIDファイル | tmp/pids/server.pid |