RUBY ON RAILS 3 Tutorial  を日本語訳してみた Chapter 8-10 2011/12/07
Ruby on Rails Tutorial とは 前に LT したときに紹介したサイト http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
前回のおさらい ユーザのログイン部分の実装の話等々 パスワード+時間をハッシュ化して保存 Twitter もどきを実装途中
目次 Chapter1 Rails 導入からデプロイ Chapter2  デモアプリ (scaffold 使用 ) Chapter3 Web アプリケーション Chapter4 Rails 風 Ruby Chapter5  スタイルを追加する Chapter6 User Model と View  その 1 Chapter7 User Model と View  その 2
目次 Chapter8  ユーザ登録 Chapter9  ログイン・ログアウト Chapter10  ユーザデータの更新・編集・追加 Chapter11  ミニブログ ( ツイート ) Chapter12  ユーザのフォロー
Chapter8 Sign up  form_for の使いかた RSpec を使ったテストの書き方 スライドに載せるには長いので割愛
Chapter8 Sign up 一旦 DB をリセット $ bundle exec rake db:reset
8.1.1 Using form_for form_for 使いかた <%=   form_for ( @user )  do  | f |   %>    < div  class= &quot;field&quot; >      <%=   f. label   :name   %> < br  />      <%=   f. text_field   :name   %>     </ div >      < div  class= &quot;actions&quot; >      <%=   f.submit  &quot; Sign up &quot;   %>     </ div > <%   end  %>  
8.1.1 Using form_for controller 側で @user = User.new 必要 f.label や f.text_field のように使う Rails2.x -> <% form_for …%> Rails3.x -> <% =  form_for …%>
言い忘れ @Chap4 BluePrint(http://blueprintcss.org/) CSS フレームワーク Tutorial ではこれを利用+ CSS 追加
言い忘れ @Chap4 BluePrint 導入 http://blueprintcss.org/ から DL DL ファイルの blueprint フォルダを app/assets/stylesheet 以下にコピー app/views/layouts/application.html.erb に追加 <%=   stylesheet_link_tag   ' blueprint/screen ' ,  :media  =>  ' screen '   %> <%=   stylesheet_link_tag   ' blueprint/print ' ,   :media  =>  ' print '   %>  
8.1.1 Using form_for BluePrint+CSS 追加、 form 完成後の状態 http://ruby.railstutorial.org/chapters/sign-up#top
8.2.1 Testing Failure users_controller_spec.rb は Tutorial 参照
8.2.3 Signup Error Messages errors.full_messages これを利用して、エラー画面を出せる $ rails console >> user = User.new(… 省略… , :email => “invalid”) >> user.save => false >>  user.errors.full_messages =>  [“Email is invalid”]
Box8.1 Integration alternatives この Tutorial では RSpec を利用 Rails 標準の Test::Unit という手段もある 1 プロジェクトに RSpec か Test::Unit を選ぶ。混ぜない
Box8.1 Integration alternatives Cucumber という手段 :RSpec と使える クライアント側のテストに有効 Cucumber を学ぶのおすすめ!
8.4.1 Integration Tests with Style spec ファイル作成 signin に失敗 / 成功用のテスト Tutorial 参照 visit signin_path や fill_in “name”, :with => “unagi” $ rake generage integration_test users
目次 Chapter8  ユーザ登録 Chapter9  ログイン・ログアウト Chapter10  ユーザデータの更新・編集・追加 Chapter11  ミニブログ ( ツイート ) Chapter12  ユーザのフォロー
Chapter9 Sign in, sign out ログインとログアウトの実装
9.1.1 Sessions controller config/routes.rb に追加 SampleApp :: Application .routes.draw  do    resources   :users    resources   :sessions ,  :only  => [ :new ,  :create ,  :destroy ]    match   ' /signup ' ,   :to  =>  ' users#new '    match   ' /signin ' ,   :to  =>  ' sessions#new '    match   ' /signout ' ,  :to  =>  ' sessions#destroy ’ # 省略 end  
9.1.1 Sessions controller セッション管理 HTTP リクエスト URL ルート名 Action 目的 GET /signin signin_path new ログイン画面 POST /sessions sessions_path create 新規セッション発行 DELETE /signout signout_path destroy セッション削除 ( ログアウト )
9.1.2 Signin form ログインフォーム作成 <%=   form_for ( :session ,  :url  => sessions_path)  do  | f |   %>    < div  class= &quot;field&quot; >      <%=   f. label   :email   %> < br  />      <%=   f. text_field   :email   %>    </ div >    < div  class= &quot;field&quot; >      <%=   f. label   :password   %> < br  />      <%=   f. password_field   :password   %>    </ div >    < div  class= &quot;actions&quot; >      <%=   f.submit  &quot; Sign in &quot;   %>    </ div > <%   end   %>  
9.2.2 Failed signin(test and code) SessionsController の create 作成    def   create     user =  User .authenticate( params [ :session ][ :email ],                               params [ :session ][ :password ])      if  user.nil?        flash .now[ :error ] =  &quot; Invalid email/password combination. &quot;        @title  =  &quot; Sign in &quot;        render   ' new '      else        # Sign the user in and redirect to the user's show page.      end    end  
9.2.2 Failed signin(test and code) authenticate() は User モデルに定義済み 認証失敗なら nil 、成功ならその user を返す flash[:error] にエラーメッセージを追加
Box 9.1 Flash dot now flash と flash.now の違い flash-> リダイレクト先まで有効 エラー時に render でエラーを表示させる場合、 render とリダイレクト後の 2 回表示されてしまう flash.now->render されたページまで有効 今回は、エラー時に render “new” しているので、 flash.now 利用 http://trwtnb.blogspot.com/2009/11/rubyrailsflashnownoticeflashnotice.html
9.3.2 Remember me まだログイン部分の話 SessionsHelper を使いたい app/helpers/application_helper.rb に追加 helper はデフォルトでは View でのみ利用可なため class   ApplicationController  <  ActionController :: Base    protect_from_forgery    include   SessionsHelper    end
9.3.3 Current user app/helpers/sessions_helper.rb に追加 sign_in, current_user, user_from_remember_token, remember_token sessions_helper.rb と User.rb の実装、テストは Tutorial 参照 github のリポジトリ https://github.com/railstutorial/sample_app
Box 9.4.What the *$@! is ||= ?  || メソッドとは nil(false) ではない方を返す。両方 true なら左の値を返す hoge =|| huga なら、 hoge が nil/false なら huga を代入 >> 1 || nil => 1 >> 2 || 1 => 2 http://www.ruby-lang.org/ja/old-man/html/Ruby_A4C7BBC8A4EFA4ECA4EBB5ADB9E6A4CEB0D5CCA3.html
Box 9.5. 10 types of people 三項演算子 true か false  ?  true なら実行 : false なら実行 例: >> a = nil ? &quot;this is true&quot;:&quot;this is false” >> puts a this is false
9 章まとめ ログイン画面 (form_for の使いかた ) セッション実装 コードが多いので、だいぶ割愛しました。ぜひ Tutorial or github のリポジトリ ( https://github.com/railstutorial/sample_app ) 参照下さい!
目次 Chapter8  ユーザ登録 Chapter9  ログイン・ログアウト Chapter10  ユーザデータの更新・編集・追加 Chapter11  ミニブログ ( ツイート ) Chapter12  ユーザのフォロー
Chapter10    Updating, showing, and deleting users ユーザ情報の更新・削除 Chapter9 と同様、実装とテストコード多め 今回は gem の紹介のみ
10.3.2 Sample users サンプルユーザ作成用 gem faker(http://faker.rubyforge.org/) Gemfile に記述 group  :development   do    gem   ‘ rspec-rails ’    gem   ‘ annotate ’ ,  :git  =>  ‘ git://github.com/ctran/annotate_models.git ’    gem   ‘ faker ’ end a
10.3.2 Sample users gem のインストール $ bundle
10.3.2 Sample users lib/tasks/sample_data.rake を作成 namespace   :db   do    desc   &quot; Fill database with sample data &quot;    task   :populate  =>  :environment   do      Rake :: Task [ ' db:reset ' ].invoke      User .create!( :name  =>  &quot; Example User &quot; ,                   :email  =>  &quot; [email_address] &quot; ,                   :password  =>  &quot; foobar &quot; ,                   :password_confirmation  =>  &quot; foobar &quot; )      99 .times  do  | n |       name  =  Faker :: Name .name       email =  &quot; example- #{ n+ 1 } @railstutorial.org &quot;       password  =  &quot; password &quot;        User .create!( :name  => name,                     :email  => email,                     :password  => password,                     :password_confirmation  => password)      end    end end  
拡大 namespace   :db   do    desc   “ Fill database with sample data ”    task   :populate  =>  :environment   do      Rake :: Task [ ‘ db:reset ’ ].invoke      User .create!( :name  =>  “ Example User ” ,                   :email  =>  “ [email_address] ” ,                   :password  =>  “ foobar ” ,                   :password_confirmation  =>  “ foobar ” )
拡大      99 .times  do  | n |       name  =  Faker :: Name .name       email =  “ example- #{ n+ 1 } @railstutorial.org ”       password  =  “ password ”        User .create!( :name  => name,                     :email  => email,                     :password  => password,                     :password_confirmation  => password)      end    end end
10.3.2 Sample users 実行 $ bundle exec rake db:populate
10.3.3 Pagination Gemfile に記述 インストール group  :development   do    gem   ‘ rspec-rails ’    gem   ‘ annotate ’ ,  :git  =>  ‘ git://github.com/ctran/annotate_models.git ’    gem   ‘ faker ’    gem   ‘ will_paginate ’ end a $ bundle
10.3.3 Pagination will_paginate (https://github.com/mislav/will_paginate)
10.3.3 Pagination app/views/users/index.html.erb < ul  class= &quot;users&quot; >    <%   @users .each  do  | user |  %>      < li >      <%=  gravatar_for user,  :size  =>  30   %>      <%=   link_to  user.name, user  %>      </ li >    <%   end   %> </ ul > <%=  will_paginate  %>  
10.3.3 Pagination app/controllers/users_controller.rb def   index      @title  =  “ All users ”      @users  =  User .paginate( :page  =>  params [ :page ]) end
10 章まとめ ユーザ情報の更新・削除の実装 github リポジトリ参照 faker や will_paginate という gem 紹介
まとめ form_for の使いかた CSS フレームワーク BruePrint 紹介 will_paginate,faker
次回予告 10 章の間に合わなかった分、次回にいれるかも 次回 11 章〜 12 章で最終回! ( のはず )

Ruby on Rails Tutorial Chapter8-10

  • 1.
    RUBY ON RAILS3 Tutorial を日本語訳してみた Chapter 8-10 2011/12/07
  • 2.
    Ruby on RailsTutorial とは 前に LT したときに紹介したサイト http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
  • 3.
  • 4.
    目次 Chapter1 Rails導入からデプロイ Chapter2 デモアプリ (scaffold 使用 ) Chapter3 Web アプリケーション Chapter4 Rails 風 Ruby Chapter5 スタイルを追加する Chapter6 User Model と View その 1 Chapter7 User Model と View その 2
  • 5.
    目次 Chapter8 ユーザ登録 Chapter9 ログイン・ログアウト Chapter10 ユーザデータの更新・編集・追加 Chapter11 ミニブログ ( ツイート ) Chapter12 ユーザのフォロー
  • 6.
    Chapter8 Sign up form_for の使いかた RSpec を使ったテストの書き方 スライドに載せるには長いので割愛
  • 7.
    Chapter8 Sign up一旦 DB をリセット $ bundle exec rake db:reset
  • 8.
    8.1.1 Using form_forform_for 使いかた <%=   form_for ( @user )  do  | f |   %>    < div  class= &quot;field&quot; >      <%=   f. label   :name   %> < br  />      <%=   f. text_field   :name   %>     </ div >     < div  class= &quot;actions&quot; >      <%=   f.submit  &quot; Sign up &quot;   %>     </ div > <%   end %>  
  • 9.
    8.1.1 Using form_forcontroller 側で @user = User.new 必要 f.label や f.text_field のように使う Rails2.x -> <% form_for …%> Rails3.x -> <% = form_for …%>
  • 10.
    言い忘れ @Chap4 BluePrint(http://blueprintcss.org/)CSS フレームワーク Tutorial ではこれを利用+ CSS 追加
  • 11.
    言い忘れ @Chap4 BluePrint導入 http://blueprintcss.org/ から DL DL ファイルの blueprint フォルダを app/assets/stylesheet 以下にコピー app/views/layouts/application.html.erb に追加 <%=   stylesheet_link_tag   ' blueprint/screen ' ,  :media  =>  ' screen '   %> <%=   stylesheet_link_tag   ' blueprint/print ' ,   :media  =>  ' print '   %>  
  • 12.
    8.1.1 Using form_forBluePrint+CSS 追加、 form 完成後の状態 http://ruby.railstutorial.org/chapters/sign-up#top
  • 13.
    8.2.1 Testing Failureusers_controller_spec.rb は Tutorial 参照
  • 14.
    8.2.3 Signup ErrorMessages errors.full_messages これを利用して、エラー画面を出せる $ rails console >> user = User.new(… 省略… , :email => “invalid”) >> user.save => false >> user.errors.full_messages => [“Email is invalid”]
  • 15.
    Box8.1 Integration alternativesこの Tutorial では RSpec を利用 Rails 標準の Test::Unit という手段もある 1 プロジェクトに RSpec か Test::Unit を選ぶ。混ぜない
  • 16.
    Box8.1 Integration alternativesCucumber という手段 :RSpec と使える クライアント側のテストに有効 Cucumber を学ぶのおすすめ!
  • 17.
    8.4.1 Integration Testswith Style spec ファイル作成 signin に失敗 / 成功用のテスト Tutorial 参照 visit signin_path や fill_in “name”, :with => “unagi” $ rake generage integration_test users
  • 18.
    目次 Chapter8 ユーザ登録 Chapter9 ログイン・ログアウト Chapter10 ユーザデータの更新・編集・追加 Chapter11 ミニブログ ( ツイート ) Chapter12 ユーザのフォロー
  • 19.
    Chapter9 Sign in,sign out ログインとログアウトの実装
  • 20.
    9.1.1 Sessions controllerconfig/routes.rb に追加 SampleApp :: Application .routes.draw  do    resources   :users    resources   :sessions ,  :only  => [ :new ,  :create ,  :destroy ]    match   ' /signup ' ,   :to  =>  ' users#new '    match   ' /signin ' ,   :to  =>  ' sessions#new '    match   ' /signout ' ,  :to  =>  ' sessions#destroy ’ # 省略 end  
  • 21.
    9.1.1 Sessions controllerセッション管理 HTTP リクエスト URL ルート名 Action 目的 GET /signin signin_path new ログイン画面 POST /sessions sessions_path create 新規セッション発行 DELETE /signout signout_path destroy セッション削除 ( ログアウト )
  • 22.
    9.1.2 Signin formログインフォーム作成 <%=   form_for ( :session ,  :url  => sessions_path)  do  | f |   %>    < div  class= &quot;field&quot; >      <%=   f. label   :email   %> < br  />      <%=   f. text_field   :email   %>    </ div >    < div  class= &quot;field&quot; >      <%=   f. label   :password   %> < br  />      <%=   f. password_field   :password   %>    </ div >    < div  class= &quot;actions&quot; >      <%=   f.submit  &quot; Sign in &quot;   %>    </ div > <%   end   %>  
  • 23.
    9.2.2 Failed signin(testand code) SessionsController の create 作成    def   create     user =  User .authenticate( params [ :session ][ :email ],                               params [ :session ][ :password ])      if  user.nil?        flash .now[ :error ] =  &quot; Invalid email/password combination. &quot;        @title  =  &quot; Sign in &quot;        render   ' new '      else        # Sign the user in and redirect to the user's show page.      end    end  
  • 24.
    9.2.2 Failed signin(testand code) authenticate() は User モデルに定義済み 認証失敗なら nil 、成功ならその user を返す flash[:error] にエラーメッセージを追加
  • 25.
    Box 9.1 Flashdot now flash と flash.now の違い flash-> リダイレクト先まで有効 エラー時に render でエラーを表示させる場合、 render とリダイレクト後の 2 回表示されてしまう flash.now->render されたページまで有効 今回は、エラー時に render “new” しているので、 flash.now 利用 http://trwtnb.blogspot.com/2009/11/rubyrailsflashnownoticeflashnotice.html
  • 26.
    9.3.2 Remember meまだログイン部分の話 SessionsHelper を使いたい app/helpers/application_helper.rb に追加 helper はデフォルトでは View でのみ利用可なため class   ApplicationController  <  ActionController :: Base    protect_from_forgery    include   SessionsHelper    end
  • 27.
    9.3.3 Current userapp/helpers/sessions_helper.rb に追加 sign_in, current_user, user_from_remember_token, remember_token sessions_helper.rb と User.rb の実装、テストは Tutorial 参照 github のリポジトリ https://github.com/railstutorial/sample_app
  • 28.
    Box 9.4.What the*$@! is ||= ? || メソッドとは nil(false) ではない方を返す。両方 true なら左の値を返す hoge =|| huga なら、 hoge が nil/false なら huga を代入 >> 1 || nil => 1 >> 2 || 1 => 2 http://www.ruby-lang.org/ja/old-man/html/Ruby_A4C7BBC8A4EFA4ECA4EBB5ADB9E6A4CEB0D5CCA3.html
  • 29.
    Box 9.5. 10types of people 三項演算子 true か false ? true なら実行 : false なら実行 例: >> a = nil ? &quot;this is true&quot;:&quot;this is false” >> puts a this is false
  • 30.
    9 章まとめ ログイン画面(form_for の使いかた ) セッション実装 コードが多いので、だいぶ割愛しました。ぜひ Tutorial or github のリポジトリ ( https://github.com/railstutorial/sample_app ) 参照下さい!
  • 31.
    目次 Chapter8 ユーザ登録 Chapter9 ログイン・ログアウト Chapter10 ユーザデータの更新・編集・追加 Chapter11 ミニブログ ( ツイート ) Chapter12 ユーザのフォロー
  • 32.
    Chapter10 Updating, showing, and deleting users ユーザ情報の更新・削除 Chapter9 と同様、実装とテストコード多め 今回は gem の紹介のみ
  • 33.
    10.3.2 Sample usersサンプルユーザ作成用 gem faker(http://faker.rubyforge.org/) Gemfile に記述 group  :development   do    gem   ‘ rspec-rails ’    gem   ‘ annotate ’ ,  :git  =>  ‘ git://github.com/ctran/annotate_models.git ’    gem   ‘ faker ’ end a
  • 34.
    10.3.2 Sample usersgem のインストール $ bundle
  • 35.
    10.3.2 Sample userslib/tasks/sample_data.rake を作成 namespace   :db   do    desc   &quot; Fill database with sample data &quot;    task   :populate  =>  :environment   do      Rake :: Task [ ' db:reset ' ].invoke      User .create!( :name  =>  &quot; Example User &quot; ,                   :email  =>  &quot; [email_address] &quot; ,                   :password  =>  &quot; foobar &quot; ,                   :password_confirmation  =>  &quot; foobar &quot; )      99 .times  do  | n |       name  =  Faker :: Name .name       email =  &quot; example- #{ n+ 1 } @railstutorial.org &quot;       password  =  &quot; password &quot;        User .create!( :name  => name,                     :email  => email,                     :password  => password,                     :password_confirmation  => password)      end    end end  
  • 36.
    拡大 namespace  :db   do    desc   “ Fill database with sample data ”    task   :populate  =>  :environment   do      Rake :: Task [ ‘ db:reset ’ ].invoke      User .create!( :name  =>  “ Example User ” ,                   :email  =>  “ [email_address] ” ,                   :password  =>  “ foobar ” ,                   :password_confirmation  =>  “ foobar ” )
  • 37.
    拡大      99.times  do  | n |       name  =  Faker :: Name .name       email =  “ example- #{ n+ 1 } @railstutorial.org ”       password  =  “ password ”        User .create!( :name  => name,                     :email  => email,                     :password  => password,                     :password_confirmation  => password)      end    end end
  • 38.
    10.3.2 Sample users実行 $ bundle exec rake db:populate
  • 39.
    10.3.3 Pagination Gemfileに記述 インストール group  :development   do    gem   ‘ rspec-rails ’    gem   ‘ annotate ’ ,  :git  =>  ‘ git://github.com/ctran/annotate_models.git ’    gem   ‘ faker ’   gem   ‘ will_paginate ’ end a $ bundle
  • 40.
    10.3.3 Pagination will_paginate(https://github.com/mislav/will_paginate)
  • 41.
    10.3.3 Pagination app/views/users/index.html.erb< ul  class= &quot;users&quot; >    <%   @users .each  do  | user |  %>      < li >      <%=  gravatar_for user,  :size  =>  30   %>      <%=   link_to  user.name, user  %>      </ li >    <%   end   %> </ ul > <%=  will_paginate  %>  
  • 42.
    10.3.3 Pagination app/controllers/users_controller.rbdef   index      @title  =  “ All users ”      @users  =  User .paginate( :page  =>  params [ :page ]) end
  • 43.
    10 章まとめ ユーザ情報の更新・削除の実装github リポジトリ参照 faker や will_paginate という gem 紹介
  • 44.
    まとめ form_for の使いかたCSS フレームワーク BruePrint 紹介 will_paginate,faker
  • 45.
    次回予告 10 章の間に合わなかった分、次回にいれるかも次回 11 章〜 12 章で最終回! ( のはず )

Editor's Notes

  • #14 どのようにテストを書くのか ユーザを作成できないとき、 new ページを表示するとき等のテストが書かれている
  • #16 ここでテストツールの話
  • #24 authenticate は渡された値のユーザが存在したときそのユーザ自身を返して、無かったときは nil を返すメソッドとして、 app/models/user.rb に定義されている