SlideShare a Scribd company logo
1 of 61
Download to read offline
Controller
              Hamamatsurb#5 2011.08.10 @mackato




11   8   16
11   8   16
Wiki

              5


11   8   16
11   8   16
11   8   16
11   8   16
11   8   16
Controller




                                - Ruby on Rails Guides
              Action Controller Overview
              : http://edgeguides.rubyonrails.org/action_controller_overview.html


11   8   16
Version 1.9.2
                           Version 3.0.9        Up!

                           Version 0.9.2        Up!

              .rvmrc
              rvm ruby-1.9.2-p180@rails-3_0_9


11   8   16
GitHub


         git clone git://github.com/hamamatsu-rb/rails3dojo.git

         git checkout -b working 2-model




11   8   16
Skinny Controller, Fat Model

              1)HTTP
               - params, request, session
              2)         Model
              3)
              - Model, flash
              4)
              - render, redirect_to



11   8   16
11   8   16
config/route.rb
     resources :sessions



     SessionsController
      #create
      #destroy




11   8   16
spec/controllers/sessions_controller_spec.rb
     describe "#create" do

         context "ログインに成功した場合" do
           before do
             @user = create_user
             post :create, :user_name => @user.name,
                  :before_path => pages_path
           end

              it "ログイン前のページにリダイレクトする" do
                response.should redirect_to(pages_path)
              end

              it "セッションにログインユーザーのidがセットされる" do
                session[:user_id].should eql(@user.id)
              end

           it "ログインユーザーの情報が取得できる" do
             controller.current_user.should eql(@user)
           end
         end

11   8   16
spec/controllers/sessions_controller_spec.rb
     describe "#create" do

         context "ログインに失敗した場合" do
           before do
             @create_user
             post :create, :user_name => "", :before_path => root_path
           end

              it "ログイン前のページにリダイレクトする" do
                response.should redirect_to(root_path)
              end

           it "エラーメッセージを表示する" do
             flash[:error].should be
           end
         end




11   8   16
spec/controllers/sessions_controller_spec.rb
     describe "#create" do

         context "存在しないユーザー名でログイン要求した場合" do
           it "ログインは成功する" do
             post :create, :user_name => "tom", :before_path => root_path
             response.should redirect_to(root_path)
           end

           it "新しいユーザーが追加される" do
             lambda do
               post :create, :user_name => "tom", :before_path => root_path
             end.should change(User, :count).by(1)
           end
         end




11   8   16
app/controllers/sessions_controller.rb
         def create
           user = User.find_or_create_by_name(params[:user_name])

              if user.valid?
                session[:user_id] = user.id
              else
                flash[:error] = user.errors.full_messages.first
              end

           redirect_to params[:before_path]
         end




11   8   16
app/controllers/application_controller.rb
     class ApplicationController < ActionController::Base
       protect_from_forgery

       def current_user
         @current_user ||= User.find(session[:user_id]) if session[:user_id]
         @current_user
       rescue ActiveRecord::RecordNotFound => e
         nil
       end
     end




11   8   16
spec/controllers/sessions_controller_spec.rb
     describe "#destroy" do

         before do
           @user = create_user
           session[:user_id] = @user.id
           delete :destroy, :id => session[:user_id],
                  :before_path => pages_path
         end

         it "ログアウト前のページにリダイレクトする" do
           response.should redirect_to(pages_path)
         end

         it "セッションのuser_idがクリアされる" do
           session[:user_id].should_not be
         end

         it "ログインユーザーの情報は取得できない" do
           controller.current_user.should_not be
         end


11   8   16
app/controllers/sessions_controller.rb

         def destroy
           session.delete(:user_id)
           redirect_to params[:before_path]
         end




11   8   16
11   8   16
config/route.rb
     resources :pages

     match ':title' => 'pages#show', :via => [:get], :as => :wiki_page




     PagesController
      #index
      #show
      #new
      #create
      #edit
      #update
      #delete

11   8   16
spec/controllers/pages_controller_spec.rb


         describe "#index" do
           before do
             create_page(:user => create_page.user)
             get :index
           end

              it "テンプレートindexを表示する" do
                response.should render_template(:index)
              end

           it "最新のPageのリストを表示する" do
             pages = assigns(:pages)
             pages.first.created_at.should > pages.last.created_at
           end
         end




11   8   16
app/controllers/pages_controller.rb
         def index
           @pages = Page.recent
         end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#show" do

              it "GET wiki_page_path(title)にマッチ" do
                { :get => wiki_page_path(:title => "Home") }.should 
                    route_to("pages#show", :title => "Home")
              end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#show" do

              context "Pageが存在する場合" do
                before do
                  @page = create_page
                  get :show, :title => @page.title
                end

               it "テンプレートshowを表示する" do
                 response.should render_template(:show)
               end

                it "タイトルが一致するPageを表示する" do
                  assigns(:page).title.should eql(@page.title)
                end
              end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#show" do

              context "Pageが存在しない場合" do
                before do
                  get :show, :title => "New Page"
                end

               it "テンプレートnewを表示する" do
                 response.should render_template(:new)
               end

               it "タイトルは入力済み" do
                 assigns(:page).title.should eql("New Page")
               end

                it "未作成Pageメッセージを表示する" do
                  flash[:notice].should be
                end
              end


11   8   16
app/controllers/pages_controller.rb
         def show
           @page = Page.find_by_title(params[:title])

           unless @page
             flash.now[:notice] = "Page was not created yet."
             @page = Page.new(:title => params[:title])
             render :action => :new
           end
         end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#new" do

              context "ログインしていない場合" do
                before do
                  request.env['HTTP_REFERER'] = pages_url
                  get :new
                end

               it "元いたページにリダイレクトする" do
                 response.should redirect_to(pages_url)
               end

                it "ログイン要求メッセージを表示する" do
                  flash[:error].should be
                end
              end




11   8   16
app/controllers/application_controller.rb
     class ApplicationController < ActionController::Base
       protect_from_forgery

         def current_user
           @current_user ||= User.find(session[:user_id]) if session[:user_id]
           @current_user
         rescue ActiveRecord::RecordNotFound => e
           nil
         end

       def login_required
         unless current_user
           flash[:error] = "This action is login required."
           url = request.env['HTTP_REFERER'] || root_url
           redirect_to url
         end
       end
     end




11   8   16
app/controllers/pages_controller.rb

     before_filter :login_required, :except => [:index, :show]




11   8   16
spec/spec_helper.rb

     def login(user_name = nil)
       user = user_name ? create_user(:name => user_name) : create_user
       session[:user_id] = user.id
     end

     def logout
       controller.instance_variable_set("@current_user", nil)
       session.delete(:user_id)
     end

     def filtered_by_login_required
       url = request.env['HTTP_REFERER'] || root_url
       response.should redirect_to(url)
       flash[:error].should be
     end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#new" do

              context "ログイン済みの場合" do
                before do
                  login
                  get :new
                end

                it "テンプレートnewを表示する" do
                  response.should render_template(:new)
                end

             it "新規Page作成フォームを表示する" do
               assigns(:page).should be_new_record
             end
           end
         end




11   8   16
app/controllers/pages_controller.rb
         def new
           @page = Page.new
         end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#create" do

              context "正しいデータが送信された場合" do
                before do
                  @before_count = Page.count
                  post :create, :page => { :title => "New Page" }
                end

                it "Wikiページにリダイレクトする" do
                  response.should redirect_to(wiki_page_path("New Page"))
                end

                it "成功メッセージが表示される" do
                  flash[:notice].should be
                end

                it "新しいPageが作成される" do
                  Page.count.should eql(@before_count + 1)
                end
              end

11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#create" do

              context "不正なデータが送信された場合" do
                before do
                  post :create, :page => { :title => "" }
                end

               it "テンプレートnewを表示する" do
                 response.should render_template(:new)
               end

                it "入力エラーメッセージを表示する" do
                  flash[:error].should be
                end
              end




11   8   16
app/controllers/pages_controller.rb
         def create
           @page = Page.new(params[:page])
           @page.user = current_user

           if @page.save
             flash[:notice] = "Page was created."
             redirect_to wiki_page_path(@page.title)
           else
             flash.now[:error] = "Page could not create."
             render :action => :new
           end
         end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#edit" do

              context "Pageが存在する場合" do
                before do
                  @page = create_page(:user => controller.current_user)
                  get :edit, :id => @page.id
                end

               it "テンプレートeditを表示する" do
                 response.should render_template(:edit)
               end

                it "Page編集フォームを表示する" do
                  assigns(:page).should_not be_new_record
                end
              end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#edit" do

              context "Pageが存在しない場合" do
                it "例外RecordNotFoundを投げる" do
                  lambda do
                    get :edit, :id => 99999
                  end.should raise_error(ActiveRecord::RecordNotFound)
                end
              end




11   8   16
app/controllers/pages_controller.rb
         def edit
           @page = Page.find(params[:id])
         end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#update" do
           context "正しいデータが送信された場合" do
             before do
               @page = create_page(:user => controller.current_user)
               @before_histries_count = @page.histories.count
               put :update, :id => @page.id, :page => { :title => "New Title" }
             end
             it "Wikiページにリダイレクトする" do
               response.should redirect_to(wiki_page_path("New Title"))
             end
             it "成功メッセージが表示される" do
               flash[:notice].should be
             end
             it "Pageが更新される" do
               assigns(:page).should be_valid
               assigns(:page).title.should eql("New Title")
             end
             it "Historyが追加される" do
               assigns(:page).histories.count.should eql(@before_histries_count + 1)
             end
           end



11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#update" do

              context "不正なデータが送信された場合" do
                before do
                  @page = create_page(:user => controller.current_user)
                  put :update, :id => @page.id, :page => { :title => "" }
                end

               it "テンプレートeditを表示する" do
                 response.should render_template(:edit)
               end

                it "入力エラーメッセージを表示する" do
                  flash[:error].should be
                end
              end




11   8   16
app/controllers/pages_controller.rb

         def update
           @page = Page.find(params[:id])
           @page.attributes = params[:page]

           if @page.save_by_user(current_user)
             flash[:notice] = "Page was updated."
             redirect_to wiki_page_path(@page.title)
           else
             flash.now[:error] = "Page could not update."
             render :action => :edit
           end
         end




11   8   16
spec/controllers/pages_controller_spec.rb
         describe "#destroy" do

              context "Pageが存在する場合" do
                before do
                  @page = create_page(:user => controller.current_user)
                  @before_count = Page.count
                  put :destroy, :id => @page.id
                end

                it "Homeにリダイレクトする" do
                  response.should redirect_to(root_path)
                end

                it "成功メッセージを表示する" do
                  flash[:notice].should be
                end

                it "Pageが削除される" do
                  Page.count.should eql(@before_count - 1)
                end
              end
11   8   16
app/controllers/pages_controller.rb
         def destroy
           @page = Page.find(params[:id])
           @page.destroy
           flash[:notice] = "Page was deleted."
           redirect_to root_path
         end




11   8   16
11   8   16
config/route.rb
     resources :pages do
       resources :comments
     end




     CommentsController
      #create
      #delete




11   8   16
spec/controllers/comments_controller_spec.rb
         describe "#create" do

              context "コメントが入力されている場合" do
                before do
                  post :create, :page_id => @page.id, 
                       :comment => { :body => "Comment...." }
                end

                it "Wikiページにリダイレクトする" do
                  response.should 
                      redirect_to(wiki_page_path(:title => @page.title))
                end

                it "成功メッセージを表示する" do
                  flash[:notice].should be
                end

                it "Commentが追加される" do
                  assigns(:page).comments.count.should eql(@before_count + 1)
                end
              end
11   8   16
spec/controllers/comments_controller_spec.rb
         describe "#create" do

           context "コメントが入力されていない場合" do
             before do
               post :create, :page_id => @page.id, 
                    :comment => { :body => "" }
             end

               it "Wikiページにリダイレクトする" do
                 response.should 
                     redirect_to(wiki_page_path(:title => @page.title))
               end

             it "エラーメッセージを表示する" do
               flash[:error].should be
             end
           end




11   8    16
app/controllers/comments_controller.rb

         before_filter :login_required

         def create
           @page = Page.find(params[:page_id])
           @comment = @page.comments.build(params[:comment])
           @comment.user = current_user

              if @comment.save
                flash[:notice] = "Comment was created."
              else
                flash[:error] = "Comment could not create."
              end

           redirect_to wiki_page_path(:title => @page.title)
         end




11   8   16
spec/controllers/comments_controller_spec.rb
         describe "#destroy" do

              context "データを正しく指定した場合" do
                before do
                  delete :destroy, :page_id => @page.id, :id => @comment.id
                end

                it "Wikiページにリダイレクトする" do
                  response.should 
                    redirect_to(wiki_page_path(:title => @page.title))
                end

                it "成功メッセージを表示する" do
                  flash[:notice].should be
                end

                it "コメントが削除される" do
                  assigns(:page).comments.count.should eql(@before_count - 1)
                end
              end

11   8   16
spec/controllers/comments_controller_spec.rb

         describe "#destroy" do

              context "データが存在しない場合" do
                it "例外RecordNotFoundを投げる" do
                  lambda do
                    delete :destroy, :page_id => 999, :id => @comment.id
                  end.should raise_error(ActiveRecord::RecordNotFound)

                  lambda do
                    delete :destroy, :page_id => @page.id, :id => 999
                  end.should raise_error(ActiveRecord::RecordNotFound)
                end
              end




11   8   16
app/controllers/comments_controller.rb

         def destroy
           @page = Page.find(params[:page_id])
           @comment = @page.comments.find(params[:id])
           @comment.destroy
           flash[:notice] = "Comment was deleted."

           redirect_to wiki_page_path(:title => @page.title)
         end




11   8   16
11   8   16
config/route.rb
     root :to => "welcome#index"




     WelcomeController
      #index




11   8   16
spec/controllers/welcome_controller_spec.rb

         describe "#index" do

              context "'Home'というタイトルのPageが存在する場合" do
                before do
                  home = create_page(:title => "Home")
                  create_page(:title => "Other", :user => home.user)
                  get :index
                end

                it "テンプレート pages/show を表示する" do
                  response.should render_template('pages/show')
                end

                it "'Home'を表示する" do
                  assigns(:page).title.should eql("Home")
                end
              end




11   8   16
spec/controllers/welcome_controller_spec.rb

         describe "#index" do

              context "Page 'Home'が存在しない場合" do
                before do
                  home = create_page(:title => "Other")
                  get :index
                end

                it "テンプレート index を表示する" do
                  response.should render_template(:index)
                end

                it "Pageはアサインされない" do
                  assigns(:page).should_not be
                end
              end




11   8   16
app/controllers/welcome_controller.rb
     class WelcomeController < ApplicationController
       def index
         @page = Page.find_by_title("Home")
         render :template => 'pages/show' if @page
       end
     end




11   8   16
git checkout master
                      git merge working
                      git branch -d working



         git clone git://github.com/hamamatsu-rb/rails3dojo.git
         git checkout 3-controller


11   8   16
11   8   16
11   8   16

More Related Content

What's hot

JavaScript Testing for Rubyists
JavaScript Testing for RubyistsJavaScript Testing for Rubyists
JavaScript Testing for RubyistsJamie Dyer
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindiaComplaints
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxWen-Tien Chang
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Sumy PHP User Grpoup
 
Ember and containers
Ember and containersEmber and containers
Ember and containersMatthew Beale
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hackingJeroen van Dijk
 
The Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressThe Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressJeroen van Dijk
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 
What's new in Rails 4
What's new in Rails 4What's new in Rails 4
What's new in Rails 4Fabio Akita
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hackingJeroen van Dijk
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in EmberMatthew Beale
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel PassportMichael Peacock
 

What's hot (20)

21.search in laravel
21.search in laravel21.search in laravel
21.search in laravel
 
Getting Started-with-Laravel
Getting Started-with-LaravelGetting Started-with-Laravel
Getting Started-with-Laravel
 
JavaScript Testing for Rubyists
JavaScript Testing for RubyistsJavaScript Testing for Rubyists
JavaScript Testing for Rubyists
 
REST API with CakePHP
REST API with CakePHPREST API with CakePHP
REST API with CakePHP
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephp
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 Ajax
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2
 
Laravel 101
Laravel 101Laravel 101
Laravel 101
 
Ember and containers
Ember and containersEmber and containers
Ember and containers
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
The Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressThe Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/Press
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
What's new in Rails 4
What's new in Rails 4What's new in Rails 4
What's new in Rails 4
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in Ember
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
 
Zend framework
Zend frameworkZend framework
Zend framework
 

Viewers also liked

From buyers inside
From buyers insideFrom buyers inside
From buyers insideDapur Pixel
 
Carp final[1]
Carp final[1]Carp final[1]
Carp final[1]slkramer
 
Softcircuitworkshop Class06
Softcircuitworkshop Class06Softcircuitworkshop Class06
Softcircuitworkshop Class06katehartman
 
Fabric softness evaluation by fabric extraction
Fabric softness evaluation by fabric extractionFabric softness evaluation by fabric extraction
Fabric softness evaluation by fabric extractionPawan Gupta
 
Process of machine embroidery
Process of machine embroideryProcess of machine embroidery
Process of machine embroideryJason Brook
 
Rumah batik prestashop theme
Rumah batik prestashop theme Rumah batik prestashop theme
Rumah batik prestashop theme Dapur Pixel
 
Fabrics in Fashion Lecture 3
Fabrics in Fashion Lecture 3Fabrics in Fashion Lecture 3
Fabrics in Fashion Lecture 3Virtu Institute
 
Types of clothing fabrics
Types of clothing fabricsTypes of clothing fabrics
Types of clothing fabricsjoannaoliv
 
Embellishment Techniques
Embellishment TechniquesEmbellishment Techniques
Embellishment TechniquesLisa Fernando
 
HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...
HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...
HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...Ajjay Kumar Gupta
 
Fabrics & their Types, Control, Quality & Cleaning
Fabrics & their Types, Control, Quality & CleaningFabrics & their Types, Control, Quality & Cleaning
Fabrics & their Types, Control, Quality & CleaningMohit Belwal
 
Fabric structure-and-design
Fabric structure-and-designFabric structure-and-design
Fabric structure-and-designMohammad furqan
 
Fabric Embellishments
Fabric Embellishments Fabric Embellishments
Fabric Embellishments Sarwat Shabbir
 
General Types of fabric
General Types of fabricGeneral Types of fabric
General Types of fabricFLI
 

Viewers also liked (16)

From buyers inside
From buyers insideFrom buyers inside
From buyers inside
 
Carp final[1]
Carp final[1]Carp final[1]
Carp final[1]
 
Softcircuitworkshop Class06
Softcircuitworkshop Class06Softcircuitworkshop Class06
Softcircuitworkshop Class06
 
Fabric softness evaluation by fabric extraction
Fabric softness evaluation by fabric extractionFabric softness evaluation by fabric extraction
Fabric softness evaluation by fabric extraction
 
Process of machine embroidery
Process of machine embroideryProcess of machine embroidery
Process of machine embroidery
 
Rumah batik prestashop theme
Rumah batik prestashop theme Rumah batik prestashop theme
Rumah batik prestashop theme
 
Fabrics in Fashion Lecture 3
Fabrics in Fashion Lecture 3Fabrics in Fashion Lecture 3
Fabrics in Fashion Lecture 3
 
Types of clothing fabrics
Types of clothing fabricsTypes of clothing fabrics
Types of clothing fabrics
 
Embellishment Techniques
Embellishment TechniquesEmbellishment Techniques
Embellishment Techniques
 
Manipulating fabric - The Art of Manipulating Fabric
Manipulating fabric - The Art of Manipulating FabricManipulating fabric - The Art of Manipulating Fabric
Manipulating fabric - The Art of Manipulating Fabric
 
HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...
HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...
HDPE / PP Woven Fabric and Sacks with Lamination and Printing, Manufacturing ...
 
Basic Hand Stitches
Basic Hand StitchesBasic Hand Stitches
Basic Hand Stitches
 
Fabrics & their Types, Control, Quality & Cleaning
Fabrics & their Types, Control, Quality & CleaningFabrics & their Types, Control, Quality & Cleaning
Fabrics & their Types, Control, Quality & Cleaning
 
Fabric structure-and-design
Fabric structure-and-designFabric structure-and-design
Fabric structure-and-design
 
Fabric Embellishments
Fabric Embellishments Fabric Embellishments
Fabric Embellishments
 
General Types of fabric
General Types of fabricGeneral Types of fabric
General Types of fabric
 

Similar to 浜松Rails3道場 其の参 Controller編

Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Pedro Cunha
 
浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編Masakuni Kato
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Prxibbar
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuLucas Renan
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - IntroductionVagmi Mudumbai
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails DevsDiacode
 
Transformando os pepinos do cliente no código de testes da sua aplicação
Transformando os pepinos do cliente no código de testes da sua aplicaçãoTransformando os pepinos do cliente no código de testes da sua aplicação
Transformando os pepinos do cliente no código de testes da sua aplicaçãoRodrigo Urubatan
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
 
Client-side Rendering with AngularJS
Client-side Rendering with AngularJSClient-side Rendering with AngularJS
Client-side Rendering with AngularJSDavid Lapsley
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Rails MVC by Sergiy Koshovyi
Rails MVC by Sergiy KoshovyiRails MVC by Sergiy Koshovyi
Rails MVC by Sergiy KoshovyiPivorak MeetUp
 
QConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações WebQConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações WebFabio Akita
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Keyguesta2b31d
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Joao Lucas Santana
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JSMartin Rehfeld
 

Similar to 浜松Rails3道場 其の参 Controller編 (20)

The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 
浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Pr
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Transformando os pepinos do cliente no código de testes da sua aplicação
Transformando os pepinos do cliente no código de testes da sua aplicaçãoTransformando os pepinos do cliente no código de testes da sua aplicação
Transformando os pepinos do cliente no código de testes da sua aplicação
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
Client-side Rendering with AngularJS
Client-side Rendering with AngularJSClient-side Rendering with AngularJS
Client-side Rendering with AngularJS
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Rails MVC by Sergiy Koshovyi
Rails MVC by Sergiy KoshovyiRails MVC by Sergiy Koshovyi
Rails MVC by Sergiy Koshovyi
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
QConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações WebQConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações Web
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Key
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 

More from Masakuni Kato

Hamackathon ideathon 2014.02.22
Hamackathon ideathon 2014.02.22Hamackathon ideathon 2014.02.22
Hamackathon ideathon 2014.02.22Masakuni Kato
 
RubyMotionでiOS開発
RubyMotionでiOS開発RubyMotionでiOS開発
RubyMotionでiOS開発Masakuni Kato
 
スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介
スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介
スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介Masakuni Kato
 
スターターライセンスではじめるAtlassian開発
スターターライセンスではじめるAtlassian開発スターターライセンスではじめるAtlassian開発
スターターライセンスではじめるAtlassian開発Masakuni Kato
 
Hamamatsu.rb.20111210
Hamamatsu.rb.20111210Hamamatsu.rb.20111210
Hamamatsu.rb.20111210Masakuni Kato
 
Twitter bootstrap on rails
Twitter bootstrap on railsTwitter bootstrap on rails
Twitter bootstrap on railsMasakuni Kato
 
リーン・スタートアップ のためのテスト
リーン・スタートアップ のためのテストリーン・スタートアップ のためのテスト
リーン・スタートアップ のためのテストMasakuni Kato
 
Start developing Facebook apps in 13 steps
Start developing Facebook apps in 13 stepsStart developing Facebook apps in 13 steps
Start developing Facebook apps in 13 stepsMasakuni Kato
 
CoffeeScript in 5mins
CoffeeScript in 5minsCoffeeScript in 5mins
CoffeeScript in 5minsMasakuni Kato
 
浜松Rails3道場 其の弐 Model編
浜松Rails3道場 其の弐 Model編 浜松Rails3道場 其の弐 Model編
浜松Rails3道場 其の弐 Model編 Masakuni Kato
 

More from Masakuni Kato (11)

Hamackathon ideathon 2014.02.22
Hamackathon ideathon 2014.02.22Hamackathon ideathon 2014.02.22
Hamackathon ideathon 2014.02.22
 
RubyMotionでiOS開発
RubyMotionでiOS開発RubyMotionでiOS開発
RubyMotionでiOS開発
 
スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介
スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介
スマートフォンを利用した会員カードシステムサービス「Smaca」のご紹介
 
スターターライセンスではじめるAtlassian開発
スターターライセンスではじめるAtlassian開発スターターライセンスではじめるAtlassian開発
スターターライセンスではじめるAtlassian開発
 
Blogging on jekyll
Blogging on jekyllBlogging on jekyll
Blogging on jekyll
 
Hamamatsu.rb.20111210
Hamamatsu.rb.20111210Hamamatsu.rb.20111210
Hamamatsu.rb.20111210
 
Twitter bootstrap on rails
Twitter bootstrap on railsTwitter bootstrap on rails
Twitter bootstrap on rails
 
リーン・スタートアップ のためのテスト
リーン・スタートアップ のためのテストリーン・スタートアップ のためのテスト
リーン・スタートアップ のためのテスト
 
Start developing Facebook apps in 13 steps
Start developing Facebook apps in 13 stepsStart developing Facebook apps in 13 steps
Start developing Facebook apps in 13 steps
 
CoffeeScript in 5mins
CoffeeScript in 5minsCoffeeScript in 5mins
CoffeeScript in 5mins
 
浜松Rails3道場 其の弐 Model編
浜松Rails3道場 其の弐 Model編 浜松Rails3道場 其の弐 Model編
浜松Rails3道場 其の弐 Model編
 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 

浜松Rails3道場 其の参 Controller編

  • 1. Controller Hamamatsurb#5 2011.08.10 @mackato 11 8 16
  • 2. 11 8 16
  • 3. Wiki 5 11 8 16
  • 4. 11 8 16
  • 5. 11 8 16
  • 6. 11 8 16
  • 7. 11 8 16
  • 8. Controller - Ruby on Rails Guides Action Controller Overview : http://edgeguides.rubyonrails.org/action_controller_overview.html 11 8 16
  • 9. Version 1.9.2 Version 3.0.9 Up! Version 0.9.2 Up! .rvmrc rvm ruby-1.9.2-p180@rails-3_0_9 11 8 16
  • 10. GitHub git clone git://github.com/hamamatsu-rb/rails3dojo.git git checkout -b working 2-model 11 8 16
  • 11. Skinny Controller, Fat Model 1)HTTP - params, request, session 2) Model 3) - Model, flash 4) - render, redirect_to 11 8 16
  • 12. 11 8 16
  • 13. config/route.rb resources :sessions SessionsController #create #destroy 11 8 16
  • 14. spec/controllers/sessions_controller_spec.rb describe "#create" do context "ログインに成功した場合" do before do @user = create_user post :create, :user_name => @user.name, :before_path => pages_path end it "ログイン前のページにリダイレクトする" do response.should redirect_to(pages_path) end it "セッションにログインユーザーのidがセットされる" do session[:user_id].should eql(@user.id) end it "ログインユーザーの情報が取得できる" do controller.current_user.should eql(@user) end end 11 8 16
  • 15. spec/controllers/sessions_controller_spec.rb describe "#create" do context "ログインに失敗した場合" do before do @create_user post :create, :user_name => "", :before_path => root_path end it "ログイン前のページにリダイレクトする" do response.should redirect_to(root_path) end it "エラーメッセージを表示する" do flash[:error].should be end end 11 8 16
  • 16. spec/controllers/sessions_controller_spec.rb describe "#create" do context "存在しないユーザー名でログイン要求した場合" do it "ログインは成功する" do post :create, :user_name => "tom", :before_path => root_path response.should redirect_to(root_path) end it "新しいユーザーが追加される" do lambda do post :create, :user_name => "tom", :before_path => root_path end.should change(User, :count).by(1) end end 11 8 16
  • 17. app/controllers/sessions_controller.rb def create user = User.find_or_create_by_name(params[:user_name]) if user.valid? session[:user_id] = user.id else flash[:error] = user.errors.full_messages.first end redirect_to params[:before_path] end 11 8 16
  • 18. app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] @current_user rescue ActiveRecord::RecordNotFound => e nil end end 11 8 16
  • 19. spec/controllers/sessions_controller_spec.rb describe "#destroy" do before do @user = create_user session[:user_id] = @user.id delete :destroy, :id => session[:user_id], :before_path => pages_path end it "ログアウト前のページにリダイレクトする" do response.should redirect_to(pages_path) end it "セッションのuser_idがクリアされる" do session[:user_id].should_not be end it "ログインユーザーの情報は取得できない" do controller.current_user.should_not be end 11 8 16
  • 20. app/controllers/sessions_controller.rb def destroy session.delete(:user_id) redirect_to params[:before_path] end 11 8 16
  • 21. 11 8 16
  • 22. config/route.rb resources :pages match ':title' => 'pages#show', :via => [:get], :as => :wiki_page PagesController #index #show #new #create #edit #update #delete 11 8 16
  • 23. spec/controllers/pages_controller_spec.rb describe "#index" do before do create_page(:user => create_page.user) get :index end it "テンプレートindexを表示する" do response.should render_template(:index) end it "最新のPageのリストを表示する" do pages = assigns(:pages) pages.first.created_at.should > pages.last.created_at end end 11 8 16
  • 24. app/controllers/pages_controller.rb def index @pages = Page.recent end 11 8 16
  • 25. spec/controllers/pages_controller_spec.rb describe "#show" do it "GET wiki_page_path(title)にマッチ" do { :get => wiki_page_path(:title => "Home") }.should route_to("pages#show", :title => "Home") end 11 8 16
  • 26. spec/controllers/pages_controller_spec.rb describe "#show" do context "Pageが存在する場合" do before do @page = create_page get :show, :title => @page.title end it "テンプレートshowを表示する" do response.should render_template(:show) end it "タイトルが一致するPageを表示する" do assigns(:page).title.should eql(@page.title) end end 11 8 16
  • 27. spec/controllers/pages_controller_spec.rb describe "#show" do context "Pageが存在しない場合" do before do get :show, :title => "New Page" end it "テンプレートnewを表示する" do response.should render_template(:new) end it "タイトルは入力済み" do assigns(:page).title.should eql("New Page") end it "未作成Pageメッセージを表示する" do flash[:notice].should be end end 11 8 16
  • 28. app/controllers/pages_controller.rb def show @page = Page.find_by_title(params[:title]) unless @page flash.now[:notice] = "Page was not created yet." @page = Page.new(:title => params[:title]) render :action => :new end end 11 8 16
  • 29. spec/controllers/pages_controller_spec.rb describe "#new" do context "ログインしていない場合" do before do request.env['HTTP_REFERER'] = pages_url get :new end it "元いたページにリダイレクトする" do response.should redirect_to(pages_url) end it "ログイン要求メッセージを表示する" do flash[:error].should be end end 11 8 16
  • 30. app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] @current_user rescue ActiveRecord::RecordNotFound => e nil end def login_required unless current_user flash[:error] = "This action is login required." url = request.env['HTTP_REFERER'] || root_url redirect_to url end end end 11 8 16
  • 31. app/controllers/pages_controller.rb before_filter :login_required, :except => [:index, :show] 11 8 16
  • 32. spec/spec_helper.rb def login(user_name = nil) user = user_name ? create_user(:name => user_name) : create_user session[:user_id] = user.id end def logout controller.instance_variable_set("@current_user", nil) session.delete(:user_id) end def filtered_by_login_required url = request.env['HTTP_REFERER'] || root_url response.should redirect_to(url) flash[:error].should be end 11 8 16
  • 33. spec/controllers/pages_controller_spec.rb describe "#new" do context "ログイン済みの場合" do before do login get :new end it "テンプレートnewを表示する" do response.should render_template(:new) end it "新規Page作成フォームを表示する" do assigns(:page).should be_new_record end end end 11 8 16
  • 34. app/controllers/pages_controller.rb def new @page = Page.new end 11 8 16
  • 35. spec/controllers/pages_controller_spec.rb describe "#create" do context "正しいデータが送信された場合" do before do @before_count = Page.count post :create, :page => { :title => "New Page" } end it "Wikiページにリダイレクトする" do response.should redirect_to(wiki_page_path("New Page")) end it "成功メッセージが表示される" do flash[:notice].should be end it "新しいPageが作成される" do Page.count.should eql(@before_count + 1) end end 11 8 16
  • 36. spec/controllers/pages_controller_spec.rb describe "#create" do context "不正なデータが送信された場合" do before do post :create, :page => { :title => "" } end it "テンプレートnewを表示する" do response.should render_template(:new) end it "入力エラーメッセージを表示する" do flash[:error].should be end end 11 8 16
  • 37. app/controllers/pages_controller.rb def create @page = Page.new(params[:page]) @page.user = current_user if @page.save flash[:notice] = "Page was created." redirect_to wiki_page_path(@page.title) else flash.now[:error] = "Page could not create." render :action => :new end end 11 8 16
  • 38. spec/controllers/pages_controller_spec.rb describe "#edit" do context "Pageが存在する場合" do before do @page = create_page(:user => controller.current_user) get :edit, :id => @page.id end it "テンプレートeditを表示する" do response.should render_template(:edit) end it "Page編集フォームを表示する" do assigns(:page).should_not be_new_record end end 11 8 16
  • 39. spec/controllers/pages_controller_spec.rb describe "#edit" do context "Pageが存在しない場合" do it "例外RecordNotFoundを投げる" do lambda do get :edit, :id => 99999 end.should raise_error(ActiveRecord::RecordNotFound) end end 11 8 16
  • 40. app/controllers/pages_controller.rb def edit @page = Page.find(params[:id]) end 11 8 16
  • 41. spec/controllers/pages_controller_spec.rb describe "#update" do context "正しいデータが送信された場合" do before do @page = create_page(:user => controller.current_user) @before_histries_count = @page.histories.count put :update, :id => @page.id, :page => { :title => "New Title" } end it "Wikiページにリダイレクトする" do response.should redirect_to(wiki_page_path("New Title")) end it "成功メッセージが表示される" do flash[:notice].should be end it "Pageが更新される" do assigns(:page).should be_valid assigns(:page).title.should eql("New Title") end it "Historyが追加される" do assigns(:page).histories.count.should eql(@before_histries_count + 1) end end 11 8 16
  • 42. spec/controllers/pages_controller_spec.rb describe "#update" do context "不正なデータが送信された場合" do before do @page = create_page(:user => controller.current_user) put :update, :id => @page.id, :page => { :title => "" } end it "テンプレートeditを表示する" do response.should render_template(:edit) end it "入力エラーメッセージを表示する" do flash[:error].should be end end 11 8 16
  • 43. app/controllers/pages_controller.rb def update @page = Page.find(params[:id]) @page.attributes = params[:page] if @page.save_by_user(current_user) flash[:notice] = "Page was updated." redirect_to wiki_page_path(@page.title) else flash.now[:error] = "Page could not update." render :action => :edit end end 11 8 16
  • 44. spec/controllers/pages_controller_spec.rb describe "#destroy" do context "Pageが存在する場合" do before do @page = create_page(:user => controller.current_user) @before_count = Page.count put :destroy, :id => @page.id end it "Homeにリダイレクトする" do response.should redirect_to(root_path) end it "成功メッセージを表示する" do flash[:notice].should be end it "Pageが削除される" do Page.count.should eql(@before_count - 1) end end 11 8 16
  • 45. app/controllers/pages_controller.rb def destroy @page = Page.find(params[:id]) @page.destroy flash[:notice] = "Page was deleted." redirect_to root_path end 11 8 16
  • 46. 11 8 16
  • 47. config/route.rb resources :pages do resources :comments end CommentsController #create #delete 11 8 16
  • 48. spec/controllers/comments_controller_spec.rb describe "#create" do context "コメントが入力されている場合" do before do post :create, :page_id => @page.id, :comment => { :body => "Comment...." } end it "Wikiページにリダイレクトする" do response.should redirect_to(wiki_page_path(:title => @page.title)) end it "成功メッセージを表示する" do flash[:notice].should be end it "Commentが追加される" do assigns(:page).comments.count.should eql(@before_count + 1) end end 11 8 16
  • 49. spec/controllers/comments_controller_spec.rb describe "#create" do context "コメントが入力されていない場合" do before do post :create, :page_id => @page.id, :comment => { :body => "" } end it "Wikiページにリダイレクトする" do response.should redirect_to(wiki_page_path(:title => @page.title)) end it "エラーメッセージを表示する" do flash[:error].should be end end 11 8 16
  • 50. app/controllers/comments_controller.rb before_filter :login_required def create @page = Page.find(params[:page_id]) @comment = @page.comments.build(params[:comment]) @comment.user = current_user if @comment.save flash[:notice] = "Comment was created." else flash[:error] = "Comment could not create." end redirect_to wiki_page_path(:title => @page.title) end 11 8 16
  • 51. spec/controllers/comments_controller_spec.rb describe "#destroy" do context "データを正しく指定した場合" do before do delete :destroy, :page_id => @page.id, :id => @comment.id end it "Wikiページにリダイレクトする" do response.should redirect_to(wiki_page_path(:title => @page.title)) end it "成功メッセージを表示する" do flash[:notice].should be end it "コメントが削除される" do assigns(:page).comments.count.should eql(@before_count - 1) end end 11 8 16
  • 52. spec/controllers/comments_controller_spec.rb describe "#destroy" do context "データが存在しない場合" do it "例外RecordNotFoundを投げる" do lambda do delete :destroy, :page_id => 999, :id => @comment.id end.should raise_error(ActiveRecord::RecordNotFound) lambda do delete :destroy, :page_id => @page.id, :id => 999 end.should raise_error(ActiveRecord::RecordNotFound) end end 11 8 16
  • 53. app/controllers/comments_controller.rb def destroy @page = Page.find(params[:page_id]) @comment = @page.comments.find(params[:id]) @comment.destroy flash[:notice] = "Comment was deleted." redirect_to wiki_page_path(:title => @page.title) end 11 8 16
  • 54. 11 8 16
  • 55. config/route.rb root :to => "welcome#index" WelcomeController #index 11 8 16
  • 56. spec/controllers/welcome_controller_spec.rb describe "#index" do context "'Home'というタイトルのPageが存在する場合" do before do home = create_page(:title => "Home") create_page(:title => "Other", :user => home.user) get :index end it "テンプレート pages/show を表示する" do response.should render_template('pages/show') end it "'Home'を表示する" do assigns(:page).title.should eql("Home") end end 11 8 16
  • 57. spec/controllers/welcome_controller_spec.rb describe "#index" do context "Page 'Home'が存在しない場合" do before do home = create_page(:title => "Other") get :index end it "テンプレート index を表示する" do response.should render_template(:index) end it "Pageはアサインされない" do assigns(:page).should_not be end end 11 8 16
  • 58. app/controllers/welcome_controller.rb class WelcomeController < ApplicationController def index @page = Page.find_by_title("Home") render :template => 'pages/show' if @page end end 11 8 16
  • 59. git checkout master git merge working git branch -d working git clone git://github.com/hamamatsu-rb/rails3dojo.git git checkout 3-controller 11 8 16
  • 60. 11 8 16
  • 61. 11 8 16