Download - Ruby on Rails Tutorial Chapter8-10
+
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
2
+前回のおさらい
ユーザのログイン部分の実装の話等々パスワード+時間をハッシュ化して保存
Twitter もどきを実装途中
3
目次
Chapter1 Rails 導入からデプロイ
Chapter2 デモアプリ (scaffold 使用 )
Chapter3 Web アプリケーション
Chapter4 Rails 風 Ruby
Chapter5 スタイルを追加する
Chapter6 User Model と View その 1
Chapter7 User Model と View その 2
4
目次
Chapter8 ユーザ登録
Chapter9 ログイン・ログアウト
Chapter10 ユーザデータの更新・編集・追加
Chapter11 ミニブログ ( ツイート )
Chapter12 ユーザのフォロー
5
+Chapter8 Sign up
form_for の使いかた
RSpec を使ったテストの書き方スライドに載せるには長いので割愛
6
+Chapter8 Sign up
一旦 DB をリセット
7
$ bundle exec rake db:reset
+8.1.1 Using form_for
form_for 使いかた
8
<%= form_for(@user) do |f| %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="actions"> <%= f.submit "Sign up" %> </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 …%>
9
+言い忘れ @Chap4
10
BluePrint(http://blueprintcss.org/)CSS フレームワークTutorial ではこれを利用+ CSS 追加
+言い忘れ @Chap4
BluePrint 導入
1.http://blueprintcss.org/ から DL
2.DL ファイルの blueprint フォルダを app/assets/
stylesheet 以下にコピー
3.app/views/layouts/application.html.erb に追加
11
<%= stylesheet_link_tag 'blueprint/screen', :media => 'screen' %><%= stylesheet_link_tag 'blueprint/print', :media => 'print' %>
+8.1.1 Using form_for
BluePrint+CSS 追加、 form 完成後の状態
12
http://ruby.railstutorial.org/chapters/sign-up#top
+8.2.1 Testing Failure
users_controller_spec.rb は Tutorial 参照
13
+8.2.3 Signup Error Messages
errors.full_messagesこれを利用して、エラー画面を出せる
14
$ 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 を選ぶ。混ぜな
い
15
+Box8.1 Integration alternatives
Cucumber という手段 :RSpec と使える
クライアント側のテストに有効
Cucumber を学ぶのおすすめ!
16
+8.4.1 Integration Tests with Style
spec ファイル作成
signin に失敗 /成功用のテストTutorial 参照
visit signin_path や fill_in “name”, :with =>
“unagi”
17
$ rake generage integration_test users
目次
Chapter8 ユーザ登録
Chapter9 ログイン・ログアウト
Chapter10 ユーザデータの更新・編集・追加
Chapter11 ミニブログ ( ツイート )
Chapter12 ユーザのフォロー
18
+Chapter9 Sign in, sign out
ログインとログアウトの実装
19
+9.1.1 Sessions controller
config/routes.rb に追加
20
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
セッション管理
21
HTTPリクエスト
URL ルート名 Action 目的
GET /signin signin_path new ログイン画面POST /sessions sessions_path create 新規セッション
発行DELETE /signout signout_path destro
yセッション削除( ログアウト )
+9.1.2 Signin form
ログインフォーム作成
22
<%= form_for(:session, :url => sessions_path) do |f| %> <div class="field"> <%= f.label :email %><br /> <%= f.text_field :email %> </div> <div class="field"> <%= f.label :password %><br /> <%= f.password_field :password %> </div> <div class="actions"> <%= f.submit "Sign in" %> </div><% end %>
+9.2.2 Failed signin(test and code)
SessionsController の create 作成
23
def create user = User.authenticate(params[:session][:email], params[:session][:password]) if user.nil? flash.now[:error] = "Invalid email/password combination." @title = "Sign in" 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] にエラーメッセージを追加
24
+Box 9.1 Flash dot now
flash と flash.now の違いflash→ リダイレクト先まで有効
エラー時に render でエラーを表示させる場合、 render
とリダイレクト後の 2 回表示されてしまう
flash.now→render されたページまで有効 今回は、エラー時に render “new” しているの
で、 flash.now 利用
25
http://trwtnb.blogspot.com/2009/11/rubyrailsflashnownoticeflashnotice.html
+9.3.2 Remember me
まだログイン部分の話
SessionsHelper を使いたいapp/helpers/application_helper.rb に追加helper はデフォルトでは View でのみ利用可な
ため
26
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
27
+Box 9.4.What the *$@! is ||= ?
|| メソッドとは
nil(false) ではない方を返す。両方 true なら左の値を返す
hoge =|| huga なら、 hoge が nil/false なら huga を代入
28
>> 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 なら実行
例:
29
>> a = nil ? "this is true":"this is false”>> puts athis is false
+9 章まとめ
ログイン画面 (form_for の使いかた )
セッション実装
コードが多いので、だいぶ割愛しました。ぜひTutorial or github のリポジトリ (https://github.com/railstutorial/sample_app) 参照下さい!
30
目次
Chapter8 ユーザ登録
Chapter9 ログイン・ログアウト
Chapter10 ユーザデータの更新・編集・追加
Chapter11 ミニブログ ( ツイート )
Chapter12 ユーザのフォロー
31
+Chapter10 Updating, showing, and deleting users
ユーザ情報の更新・削除
Chapter9 と同様、実装とテストコード多め今回は gem の紹介のみ
32
+10.3.2 Sample users
サンプルユーザ作成用 gemfaker(http://faker.rubyforge.org/)
Gemfile に記述
33
group :development do gem ‘rspec-rails’ gem ‘annotate’, :git => ‘git://github.com/ctran/annotate_models.git’ gem ‘faker’enda
+10.3.2 Sample users
gem のインストール
34
$ bundle
+10.3.2 Sample users
lib/tasks/sample_data.rake を作成
35
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 protected]", :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 endend
+拡大
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 protected]”, :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 endend
+10.3.2 Sample users
実行
38
$ bundle exec rake db:populate
+10.3.3 Pagination
Gemfile に記述
インストール
39
group :development do gem ‘rspec-rails’ gem ‘annotate’, :git => ‘git://github.com/ctran/annotate_models.git’ gem ‘faker’ gem ‘will_paginate’enda
$ bundle
+10.3.3 Pagination
will_paginate
(https://github.com/mislav/will_paginate)
40
+10.3.3 Pagination
app/views/users/index.html.erb
41
<ul class="users"> <% @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
42
def index @title = “All users” @users = User.paginate(:page => params[:page])end
+10 章まとめ
ユーザ情報の更新・削除の実装github リポジトリ参照
faker や will_paginate という gem
紹介
43
+まとめ
form_for の使いかた
CSS フレームワーク BruePrint 紹介
will_paginate,faker
44
+次回予告
10 章の間に合わなかった分、次回にいれるかも
次回 11 章〜 12 章で最終回! ( のはず )
45