Upload
sea-mountain
View
2.232
Download
6
Embed Size (px)
DESCRIPTION
I try to Ruby on Rails tutorial in Japanese. This is Chap5 to 7.
Citation preview
+
RUBY ON RAILS 3 Tutorial を日本語訳してみたChapter 5-7
2011/11/10
+おさらい
前回 Chapter4を軽く飛ばしました rails consoleコマンドの話 Rubyの文法的部分の話だったので、このまま飛ばします
Chapter3では TDD(Test Driven Development)
2
目次
Chapter1 Rails導入からデプロイ
Chapter2 デモアプリ (scaffold使用 )
Chapter3 Webアプリケーション
Chapter4 Rails風 Ruby
Chapter5 スタイルを追加する
Chapter6 User Modelと View その 1
Chapter7 User Modelと View その 2
3
目次
Chapter8 ユーザ登録
Chapter9 ログイン・ログアウト
Chapter10 ユーザデータの更新・編集・追加
Chapter11 ミニブログ ( ツイート )
Chapter12 ユーザのフォロー
4
+Chapter5 Filling in the Layout
CSSを追加する話
レイアウトの話なので、気になった所のみ
5
+5.2.1 Integration Tests
routes.rbを触る前に Integration test(結合テスト ) を行う
テスト用 specファイル作成
※RSpecでは integration testsのことを request specs
と言う
6
$ rails generate integration_test layout_links invoke rspec create spec/requests/layout_links_spec.rb
+5.2.1 Integration Tests
spec/requests/layout_links_spec.rb
に以下のテストを追加
7
describe "GET 'home'" do it "should be successful" do get 'home' response.should be_success endend
+5.2.1 Integration Tests
自動でテストが実行されない場合 .autotestに追加
Mac OS Xの場合
8
Autotest.add_hook :initialize do |autotest| autotest.add_mapping(/^spec\/requests\/.*_spec\.rb$/) do autotest.files_matching(/^spec\/requests\/.*_spec\.rb$/) endend
+5.2.1 Integration Tests
Ubuntuか Linuxの場合
9
Autotest.add_hook :initialize do |autotest| autotest.add_mapping(%r%^spec/(requests)/.*rb$%) do|filename, _| filename endend
+5.2.2 Rails Routes
URLマッピングは config/routes.rbで
routes.rb例:
:to => ‘コントローラ名# アクション名’
10
SampleApp::Application.routes.draw do match '/contact', :to => 'pages#contact' match '/about', :to => 'pages#about' match '/help', :to => 'pages#help'end
+5.4 Conclusion
CSSの当て方
route.rbの使い方
link_toの使いかた
11
目次
Chapter1 Rails導入からデプロイ
Chapter2 デモアプリ (scaffold使用 )
Chapter3 Webアプリケーション
Chapter4 Rails風 Ruby
Chapter5 スタイルを追加する
Chapter6 User Modelと View その 1
Chapter7 User Modelと View その 2
12
+Chapter6 Modeling and
Viewing Users, PartⅠ
( 前提 ) ユーザがログインするシステムを作っている途中
ユーザモデルの作成
DBのテーブル作成
バリデーション
13
+Box 6.1 Roll Your Own Authentication
System
OpenIDや OAuth
Railsに備わっている認証モジュール
それらを使わずに認証を自作すべし
14
+
Railsの認証に答えが無いからチュートリアルで扱っても時代遅れになる可能性
正しい方法を示しても、古くなってしま
う
Railsと認証の両方の勉強になる
15
Box 6.1 Roll Your Own Authentication System
+6.1.1 Database Migration
Userコントローラ作成 (newアクション付き )
Userモデル作成 (nameと emailを持ってい
る )
16
$ rails g controller Users new
$ rails g model User name:string email:string
+6.1.1 Database Migration
DB作成
DB削除
17
$ bundle exec rake db:migrate
$ bundle exec rake db:rollback
“bundle execを使うと、 BUNDLE_PATH以下のgem ”を使って、スクリプトを実行できます。(http://d.hatena.ne.jp/mirakui/20100703/1278165723)
+6.1.2 The Model File
Model Annotation
annotateという gemを入れるGemfileに’ annotate’追加※注意 :git=>以下を追加しないと 3.1系で動かないhttps://github.com/ctran/annotate_models/issues/28
18
group :development do gem 'rspec-rails' gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'end
+6.1.2 The Model File
実行結果
19
$ bundle exec annotate --position before
# == Schema Information## Table name: users## id :integer not null, primary key# name :string(255)# email :string(255)# created_at :datetime# updated_at :datetime#
class User < ActiveRecord::Baseend
追加されている
+6.1.3 Creating user objects
--sandboxで DBには変更を加えない
-fオプションで常に最新のログを見れる
20
$ rails console --sandbox
$ tail –f log/development.log
+6.2 User Validations
TDDのため、 development DBの構造をtest DBに反映させる
21
$ bundle exec rake db:test:prepare
+6.2.3 Format Validation
email等のバリデーション用正規表現
Rubular(http://rubular.com/)正規表現の入力
→マッチするか確認
22
+6.2.3 Format Validation
余談 (Gmailの場合 )
例えば…
+ やスペースなどのメールアドレスに使えない記号もバリデーションで許可必要
23
[email protected] == test+hoge@gmail+ から@ 前までが無視される
+6.3.1 Debug and Rails Environments
Railsの環境test(テスト用 )
development(開発用 ) app以下のコード変更が常に反映される
production(本番環境 )コード変更反映にはサーバーの再起動必要。こちらのほうが早い
http://d.hatena.ne.jp/zariganitosh/20070108/1168246932
24
+6.3.1 Debug and Rails Environments
Rails consoleのデフォルトはdevelopment
consoleで以下のメソッドで確認可能
25
>> Rails.env=> “development”
>> Rails.env.development?=> “true”
>> Rails.env.test?=> “false”
+6.3.1 Debug and Rails Environments
環境を指定して実行出来る
Railsを動かすときも環境指定可能
26
$ rails console test
$ rails server --environment production
+6.3.1 Debug and Rails Environments
production環境の DBを構築する
ちなみにheroku consoleで試すと、 Herokuはproduction環境であることが分かる
27
$ bundle exec rake db:migrate RAILS_ENV=production
目次
Chapter1 Rails導入からデプロイ
Chapter2 デモアプリ (scaffold使用 )
Chapter3 Webアプリケーション
Chapter4 Rails風 Ruby
Chapter5 スタイルを追加する
Chapter6 User Modelと View その 1
Chapter7 User Modelと View その 2
28
+
ユーザのログイン周りパスワード暗号化
ユーザの個人ページ作成Gravatarを利用する gem
29
Chapter7 Modeling and Viewing Users, PartⅡ
+7.2.2 Some Secure Password Theory
ユーザのログインパスワードハッシュ化して比較
30
+7.2.2 Some Secure Password Theory
31
$ rails console >> require 'digest' >> def secure_hash(string) >> Digest::SHA2.hexdigest(string) >> end
>> password = "secret" >> encrypted_password = secure_hash(password) “2bb80d537b1da3e38bd30361aa85…(省略 )"
>> submitted_password = "secret" >> encrypted_password == secure_hash(submitted_password)
=> true
+7.2.2 Some Secure Password Theory
rainbow attack( 事前計算攻撃 /レインボー攻撃 ) http://michisugara-aud.sakura.ne.jp/lectures/
lectures_25.html
パスワードが類推される可能性がある
→salt( 今回は現在時刻の文字列 ) を利用するハッシュ関数 (pass)をハッシュ関数 ( 時刻
+pass)に
32
+ 33
7.2.2 Some Secure Password Theory
>> Time.now.utc => Fri Jan 29 18:11:27 UTC 2010
>> password = "secret" => "secret"
>> salt = secure_hash("#{Time.now.utc}--
#{password}") =>
"d1a3eb8c9aab32ec19cfda810d2ab351873b5dca4e16e7f57b3c19321133
14c8"
>> encrypted_password = secure_hash("#{salt}--
#{password}")
=> "69a98a49b7fd103058639be84fb88c19c998c8ad3639cfc5deb458018561c847"
※明確にするため、ハッシュ化する文字列は” --”で区切られるらしい
+7.2.3 Implementing has_password?
Userモデルに saltフィールド追加する
migrationの設定
db/migrate/<timestamp>_add_salt_to_users.rbが作成される
migration名 (add_password_to_users)は自由
※_to_usersにしておくと、自動でUserに追加される!便利!
34
$ rails generate migration add_password_to_users encrypted_password:string
+
作成したmigrationの実行
35
7.2.3 Implementing has_password?
$ bundle exec rake db:migrate$ bundle exec rake db:test:prepare
sqlite> .schemaCREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "email" varchar(255), "created_at" datetime, "updated_at" datetime, "salt" varchar(255));
+7.3.2 A Name and a Gravatar
Gemfileにgravatar_image_tag追加 Gravatar(http://gravatar.com)を利用する gem
<%= gravatar_image_tag ‘email’ %>これだけで、登録された emailのアイコンを表示してくれる
← Gravatarに登録がない場合に表示される
36
+今回のまとめ
5 章では CSSの導入的な話
Userモデルの作り方について、6・ 7章だった
全体的にざっくり削った Tutorialではちゃんとテストする過程がある
RSpecのコードも載っていたが割愛
Heroku・Gitも使っている ( 章毎に pushしている )
37
+次回予告
8章 Sign Up 新規登録
9章 Sign In, Sign Outs セッション周り
10章 Updating, Showing, and Deleting Users
うまく行けば、次の次の回で最終回…? ( 全 12章 )
38