512

Ruby on Rails tutorial 3rd 中文版

Embed Size (px)

DESCRIPTION

Ruby on Rails tutorial 3rd 中文版

Citation preview

  • Ruby on Rails Rails Web

    Michael Hartl

    . 3

    rev 1.0.2, 2015-01-14T20:00:00+08:00

  • =)

    .w

    1 +................................................................................................................... 11.1.) 21.2. 51.3. 71.4.> Git Gi 201.5. 291.6. 331.7. 33

    2 S .......................................................................................................................................... 352.1.` 352.2. 382.3.y 492.4. 582.5. 59

    3 ............................................................................................................................... 633.1.d 633.2. 653.3. 733.4.pT 783.5. 873.6. 883.7. 90

    4 Rails Ruby ........................................................................................................................... 974.1. 974.2. 100

    v

  • 4.3.R- 1064.4. Ruby 1154.5. 1234.6. 123

    5 ........................................................................................................................................ 1255.1.n" 1255.2. Sass Asset Pipeline 1405.3. 1485.4.U 1545.5. 1575.6. 158

    6 ........................................................................................................................................ 1616.1. 1616.2. 1706.3.nO 1836.4. 1896.5. 190

    7 U ............................................................................................................................................... 1937.1.C 1937.2.Ux 2067.3.U 2137.4.Um 2237.5. 2317.6. 2347.7. 235

    8 [ .................................................................................................................................... 2398.1.5 2398.2. 2508.3.[ 2638.4.; 2658.5. 2888.6. 289

    9 f .................................................................................................................. 2939.1. 2939.2. 303

    vi -

  • 9.3.a[ 3159.4.f 3279.5. 3349.6. 336

    10 .................................................................................................................... 33910.1. 33910.2. 36410.3.$1 38610.4. 38810.5. 38810.6. 391

    11 y .................................................................................................................................. 39311.1.y 39311.2.y 40211.3.yQ= 41211.4.y 43111.5. 44211.6. 444

    12 Q ...................................................................................................................................... 44712.1. Q 45212.2.Q 46112.3.p 48512.4. 49312.5. 493

    - vii

  • Ruby T@*David Heinemeier Hansson 1 Rails 1 RubyRails d Ruby on Rails Web E&,E&Ruby on Rails Tutorial."Cg Rails Web

    8 Web "i Ru-by on Rails -\-V"Ruby on Rails Tutorial

    E\V.;

    eL

    Michael HartlRuby on Rails Tutoriald

    Ruby is a delightful computer language explicitly designed to make programmers happy. This philosophy influencedDavid Heinemeier Hansson to pick Ruby when implementing the Rails web framework. Ruby on Rails, as its oftencalled, makes building custom web applications faster and easier than ever before. In the past few years, the Ruby onRails Tutorial has become the leading introduction to web development with Rails.

    In our interconnected world, computer programming and web application development are rapidly rising in impor-tance, and I am excited to support Ruby on Rails in China. Although it is important to learn English, which is the in-ternational language of programming, its often helpful at first to learn in your native language. It is for this reasonthat I am grateful to Andor Chen for producing the Chinese-language edition of the Ruby on Rails Tutorial book.

    Ive never been to China, but I definitely plan to visit some day. I hope Ill have the chance to meet some of you whenI do!

    Best wishes and good luck,

    Michael HartlAuthor

    The Ruby on Rails Tutorial

    ix

  • (dCD Baby Ruby on Rails Q(1PHP Google 6@ Michael Hartl .KRuby on Rails Tutorialg Rails z1

    Rails .\1.Rails (K\..,gTest-driven Development TDD Rails .g TDD\.([email protected] GitBitbucket Herokude`1A&.I

    11.1.,z1-EE

    >.

    Derek Sivers (sivers.org)CD Baby @

    1. .

    xi

  • Ruby on Rails 6K.RailsSpaceK@ AureliusProchazka, AureHB".z1,21. Debra Williams Cauley RailsSpace .V".

    Ruby ;HL,HLDavid Heinemeier Hans-sonYehuda KatzCarl LercheJeremy KemperXavier NoriaRyan BatesGeoffrey GrosenbachPeterCooperMatt AimonettiMark BatesGregg PollackWayne E. SeguinAmy HoyDave ChelimskyPatMaddoxTom Preston-WernerChris WanstrathChad FowlerJosh SusserObie FernandezIan McFarlandSteven BristolPratik NaikSarah MeiSarah AllenWolfram ArnoldAlex ChaffeeGiles BowkettEvanDornLong NguyenJames LindenbaumAdam WigginsTikhon BernstamRon EvansWyatt GreeneMiles ForrestPivotal Labs @LHeroku thoughtbot UYK GitHub `1$.d1S1;@K.

    xiii

  • =)

    .dMichael Hartl Ruby on Rails Web C@(,SoftCover@H(d1 RailsSpace Rails ,g Ruby onRails " Insoshi

  • .w

    .Ruby on Rails Tutorial: Learn Web Development with Rails (Third Edition).`dMichael Hartl Michael Hartl

    .oOa@KOazg

    .I6MIT Beerware

    The MIT License

    Copyright (c) 2014 Michael Hartl

    Permission is hereby granted, free of charge, to any person obtaining a copy

    of this software and associated documentation files (the "Software"), to deal

    in the Software without restriction, including without limitation the rights

    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

    copies of the Software, and to permit persons to whom the Software is

    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in

    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

    THE SOFTWARE.

    /*

    * ----------------------------------------------------------------------------

    * "THE BEERWARE LICENSE" (Revision 43):

    * Michael Hartl wrote this code. As long as you retain this notice you

    * can do whatever you want with this stuff. If we meet some day, and you think

    * this stuff is worth it, you can buy me a beer in return.

    * ----------------------------------------------------------------------------

    */

    xvii

  • 1 +

    Ruby on Rails Rails - Web .ea Web L Ruby on Rails Web e.VeC Web RubyRailsHTML CSSKV;"eP Web dKe"e1 Web.V Rails MVC RESTK Ru-by.(Ke.;1

    . Web -Lhello_app1.3 5; toy_app 2 sam-ple_app 3 12 EK.6[V,g Rails.CKeA& Web .

    @LV.- Web 1.1.1 z1Web Oa". Web \Ke.z1^1 Rails

    1.1:

    .1^ Rails

    g71.2 1

    Rails iMh MiniTest

    1jMRSpecCucumberCapybaraFactory Girl

    g

    C1"GuardSporkRubyTest

    Rails Web

    ;.

    L Ruby on Rails KM1.2 Rails hello_app.CTM-K(LV

    1. .K. http://railstutorial-china.orge

    1

  • Git 1.4 epL1.5

    2 V5 Rails ;d"1LVg 1.2" toy_app"I,K 2 gURI" URL2

  • Heinemeier HanssonVh Rails Merb E Rails 1 Merb API,1

    Rails KKVSV1 gemI gem hWK; IRC S Rails ,g1)

    1.1.1.

    ..BC Rails Ruby Rails gMiniTestUnix JHTMLCSS JavaScriptK SQLLK.(; HTML &\,g.E- Web Kmeee_1KgE]HLz\z51

    - Rails @ Ruby6e@-Ke"-eKE& Ruby - RubyChris Pine Learn to Program Peter Cooper Ruby Rails Web (C Ruby .e@e Try Ruby-;

  • 1.2 Vegd Windowsg71.2.11 UnixLinuxJJ" Rails i1KJJh 1.3.2 LVg rails serverJ Web

    $ rails server

    J.,Vg Unix /hMproduction.rb

    config/environments/production.rb

    M6V7 IDE

    /home/ubuntu/workspace/sample_app/

    Kproduction.rb

    /home/ubuntu/workspace/sample_app/config/environments/production.rb

    "1V config/environments/production.rb

    .;Hshell JRuby "(e.\;J;dV.V;eK,"Mze.1e.

    L Rails KIMgg"1mIgREDIgGREEN

    ;-eKz\z"1--Vg-IV

    "1m.gI;I?I

    class User < ActiveRecord::Base

    validates :name, presence: true

    validates :email, presence: true

    end

    ?I6II},II5"1.I

    class User < ActiveRecord::Base

    .

    .

    .

    has_secure_password

    end

    ;I

    4 - 1 +

  • 1.2.

    Rails RubyRailsKM,;dyIntegratedDevelopment Environment IDEVe1Kge\6g7 1.1K7 IDE Web Rails dh WindowseD-.e InstallRails.com4

    1.2.1.

    @ Rails "1.g7Cloud9"1 Cloud9 d".11 Rails M RubyRubyGems Git Rails&z 1.2.2 7 IDE Web MMKJ 1.17 IDE M5 Rails

    1.1! IDE

    7g

    4. Windows InstallRails g Rails .5. h foo'`Kdef foo

    1.2. - 5

  • 1. Cloud9

    2. Go to your Dashboard

    3. Create New Workspaced

    4. "rails-tutorialrails_tutorialdPrivate to the people I inviteB

    @ Rails Ruby on Rails 1.2

    5. Create

    6. Cloud9 ddStart editing

    1.2 Cloud9 =

    "g) Ruby Keq"Code Editor (Ace)Ace ISoftTabs 1.3qSave

    6 - 1 +

  • 1.3 Cloud9 >

    1.2.2. Rails

    M\ Rails6"1 RailsLg RubyGems i gemJJI 1.1JJg7 IDE 1.1JJ

    .x 1.1 Rails

    $ gem install rails -v 4.2.0

    -vd Rails eg-e

    1.3.

    Whello, world`L hello, world!1.3.4 1.5

    Rails E rails newJJVeM Rails g1.2.1 Cloud9 IDEeM" workspaceMI

    6. Cloud9 i Rails .K

    1.3. - 7

  • 1.2I 1.2g1 Unix J cd mkdire;JK1.3

    .x 1.2 Rails 1 workspace!

    $ cd # N$ mkdir workspace # workspace 1$ cd workspace/ # N workspace 1

    1.3Unix /

    g Windows Mac OS X\ Unix Jg7i1 UnixLinuxJ shell J Bash

    JgJdhMmkdirMmv cpKMcd#gGraphical User InterfaceGUIJ1J(eVJ shell

    \.V; Unix JJ 1.1- Unix J Mark Bates Conquering the Command LineK,K/.

    1.1" Unix /

    = / ?

    ls $ ls -l

    M mkdir $ mkdir workspace

    cd $ cd workspace/

    $ cd ..

    $cd ~ $ cd

    M $ cd ~/workspace/

    M mv $ mv README.rdoc README.md

    M cp $ cp README.rdoc README.md

    M rm $ rm README.rdoc

    M rmdir $ rmdir workspace/

    M rm -rf $ rm -rf tmp/

    M cat $ cat ~/.ssh/id_rsa.pub

    7 IDE gI 1.3JIL1 Rails 4.2.0&zogI 1.1

    8 - 1 +

  • Rails MI 1.3JCould not find railtiese Rails e Rails JI 1.1

    .x 1.3 rails new/

    $ cd ~/workspace

    $ rails _4.2.0_ new hello_app

    create

    create README.rdoc

    create Rakefile

    create config.ru

    create .gitignore

    create Gemfile

    create app

    create app/assets/javascripts/application.js

    create app/assets/stylesheets/application.css

    create app/controllers/application_controller.rb

    .

    .

    .

    create test/test_helper.rb

    create tmp/cache

    create tmp/cache/assets

    create vendor/assets/javascripts

    create vendor/assets/javascripts/.keep

    create vendor/assets/stylesheets

    create vendor/assets/stylesheets/.keep

    run bundle install

    Fetching gem metadata from https://rubygems.org/..........

    Fetching additional metadata from https://rubygems.org/..

    Resolving dependencies...

    Using rake 10.3.2

    Using i18n 0.6.11

    .

    .

    .

    Your bundle is complete!

    Use `bundle show [gemname]` to see where a bundled gem is installed.

    run bundle exec spring binstub --all

    * bin/rake: spring inserted

    * bin/rails: spring inserted

    I 1.3 rails newJM(V bundle installJLV1.3.1 Jd

    rails newJMMM 1.4 Rails ST(eE Rails gMKH@I;Md 1.2.CMME 5.2.1 LC app/assetsM Asset Pipeline AssetPipeline CSS JavaScript M

    1.3. - 9

  • 1.4 Rails 1

    1.2Rails 1)

    1/1 =

    app/ M

    app/assets MhCSSJavaScript

    bin/ 5M

    config/

    db/ M

    doc/

    lib/ IM

    lib/assets IMh CSSJavaScript

    log/ M

    public/ hMh

    bin/rails IV

    test/

    tmp/ !M

    10 - 1 +

  • 1/1 =

    vendor/ IhM gem

    vendor/assets Mh CSSJavaScript

    README.rdoc C

    Rakefile g rakeJO

    Gemfile gem

    Gemfile.lock gem og gem

    config.ru Rack MM

    .gitignore Git M

    1.3.1. Bundler

    Rails g Bundler gem 1.3 rails newJV Bundler bundle installJLqg gem BundlerM Gemfile`\I 1.4 1.5M Ruby I 4 VC Rubye 1.5 MMMRefresh File TreeMMMKM

    .x 1.4hello_app Gemfile

    source 'https://rubygems.org'

    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'

    gem 'rails', '4.2.0'

    # Use sqlite3 as the database for Active Record

    gem 'sqlite3'

    # Use SCSS for stylesheets

    gem 'sass-rails', '~> 5.0.0.beta1'

    # Use Uglifier as compressor for JavaScript assets

    gem 'uglifier', '>= 1.3.0'

    # Use CoffeeScript for .js.coffee assets and views

    gem 'coffee-rails', '~> 4.0.0'

    # See https://github.com/sstephenson/execjs#readme for more supported runtimes

    # gem 'therubyracer', platforms: :ruby

    # Use jquery as the JavaScript library

    gem 'jquery-rails'

    # Turbolinks makes following links in your web application faster. Read more:

    # https://github.com/rails/turbolinks

    gem 'turbolinks'

    # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder

    gem 'jbuilder', '~> 2.0'

    # bundle exec rake doc:rails generates the API under doc/api.

    gem 'sdoc', '~> 0.4.0', group: :doc

    1.3. - 11

  • # Use ActiveModel has_secure_password

    # gem 'bcrypt', '~> 3.1.7'

    # Use Unicorn as the app server

    # gem 'unicorn'

    # Use Capistrano for deployment

    # gem 'capistrano-rails', group: :development

    group :development, :test do

    # Call 'debugger' anywhere in the code to stop execution and get a

    # debugger console

    gem 'byebug'

    # Access an IRB console on exceptions page and /console in development

    gem 'web-console', '~> 2.0.0.beta2'

    # Spring speeds up development by keeping your application running in the

    # background. Read more: https://github.com/rails/spring

    gem 'spring'

    end

    I #1;I"1e; gem,"1 Bundler1; gem (LH gem

    gemJBundler Vh

    gem 'sqlite3'

    gem Rails gI

    gem 'uglifier', '>= 1.3.0'

    I66 1.3.0 uglifierd Asset Pipeline M 7.2,V5

    gem 'coffee-rails', '~> 4.0.0'

    12 - 1 +

  • 1.5 Gemfile

    I6 4.0.0\6 4.1 coffee-rails,>=~> 4.0.0hE 4.0.0 4.0.1#hE 4.0 4.1Lg,KLV" gem eKgOa gem KGemfileg ~>g\4eV

    qI 1.4 GemfileI 1.5uVL1 sqlite3]7.1.1 Heroku 1.5

    .x 1.5 Ruby gem > Gemfile

    source 'https://rubygems.org'

    gem 'rails', '4.2.0'

    gem 'sass-rails', '5.0.0.beta1'

    gem 'uglifier', '2.5.3'

    gem 'coffee-rails', '4.1.0'

    gem 'jquery-rails', '4.0.0.beta2'

    gem 'turbolinks', '2.3.0'

    gem 'jbuilder', '2.2.3'

    gem 'sdoc', '0.4.0', group: :doc

    group :development, :test do

    1.3. - 13

  • gem 'sqlite3', '1.3.9'

    gem 'byebug', '3.4.0'

    gem 'web-console', '2.0.0.beta3'

    gem 'spring', '1.1.3'

    end

    I 1.5 GemfileM( bundle installJ7; gem

    $ cd hello_app/

    $ bundle install

    Fetching source index for https://rubygems.org/

    .

    .

    .

    bundle installJVLK1

    1.3.2. rails server

    1.3 rails newJ 1.3.1 bundle installJ(LK1\&Rails 1JKLdJ`&6eg rails serverJI1.6 Cloud9 IP Rails KI 1.78Cloud9 g $IP $PORT IP vKJ echo $IP echo $PORT

    .x 1.6 Rails o

    $ cd ~/workspace/hello_app/

    $ rails server

    => Booting WEBrick

    => Rails application starting on http://localhost:3000

    => Run `rails server -h` for more startup options

    => Ctrl-C to shutdown server

    .x 1.7! IDE Rails o

    $ cd ~/workspace/hello_app/

    $ rails server -b $IP -p $PORT

    => Booting WEBrick

    => Rails application starting on http://0.0.0.0:8080

    => Run `rails server -h` for more startup options

    => Ctrl-C to shutdown server

    ge rails serverJeKHJ1 1.6 1.7e1KCtrl-C http://localhost:3000/7 IDE

    7. 3.1K install" bundle bundle install8. g 80 \K"1mg

    14 - 1 +

  • Share>Application 1.8 1.9[

    1.6Vz

    About your applications environmentKpe\1.101EL Rails Rails K1LV1.3.4 L

    1.3. - 15

  • 1.7z Rails o

    1.8^%!=o

    16 - 1 +

  • 1.9 rails server/h Rails

    1.10C

    1.3. - 17

  • 1.3.3.--i

    Rails d 1.11V;e1 Rails MM app/ 1.4Mmodelsviews con-trollers Rails 1-- MVCdomainlogic,business logic Web GUI

    1.11MVC

    Rails

  • 1.3.4. Hello, world!

    Lg MVC z;d hello, world!E 2.2.2 VCdghello, world! Rails 1.9

    EdKd'L ApplicationController'd" helloL ApplicationControllerJKE 2 LV

    $ ls app/controllers/*_controller.rb

    hellod'`I 1.8 renderhello, world! Ruby 4 VC

    .x 1.8 ApplicationControllern hellop=app/controllers/application_controller.rb

    class ApplicationController < ActionController::Base

    # Prevent CSRF attacks by raising an exception.

    # For APIs, you may want to use :null_session instead.

    protect_from_forgery with: :exception

    def hello

    render text: "hello, world!"

    end

    end

    ' d(L Rails gd 1.10"Lq Rails ( 1.11d 1.111E 2.2.2 VC`Lq, URL URL http://www.example.com/ Kg /

    I 1.9Rails Mconfig/routes.rbawelcomeindexd #K'1I 1.10I Rails

  • .x 1.10config/routes.rb

    Rails.application.routes.draw do

    .

    .

    .

    # You can have the root of your site routed with "root"

    root 'application#hello'

    .

    .

    .

    end

    1I 1.8I 1.10IVLhello, world!1 1.12

    1.12hello, world!

    1.4.> Git Gi

    L1K Rails zM4M4\M"4IKIm6H@dh1MKKM-g

    20 - 1 +

  • Rails g GitGit Linus Torvalds Linux IGit .VC; Scott Chacon Pro Git9(Kg Git zB" Rails "g Git >I1.4.3 ,m61.5

    1.4.1.

    1.2.1 g7 IDE Giteg7 IDEK Install-Rails.com Git

    kG

    gGit z;;

    $ git config --global user.name "Your Name"

    $ git config --global user.email [email protected]

    $ git config --global push.default matching

    $ git config --global alias.co checkout

    Git MVFz"1 Git 1Kg coI checkoutJ"1 co.Dg checkoutgit co

    >,kG

    FF

    $ git init

    Initialized empty Git repository in /home/ubuntu/workspace/hello_app/.git/

    git add -AJMF

    $ git add -A

    JVMF\M .gitignoreMrails newJV6 Rails .gitignoreMeKH10

    FM]6staging area6 Git Gi - 21

  • new file: .gitignore

    new file: Gemfile

    new file: Gemfile.lock

    new file: README.rdoc

    new file: Rakefile

    .

    .

    .

    Kg1;

    Git o;Kg commitJ

    $ git commit -m "Initialize repository"

    [master (root-commit) df0a62f] Initialize repository

    .

    .

    .

    -m"

  • Changed but not updated:

    (use "git add/rm ..." to update what will be committed)

    (use "git checkout -- ..." to discard changes in working directory)

    deleted: app/controllers/application_controller.rb

    no changes added to commit (use "git add" and/or "git commit -a")

    K1M\d Git F.g GitHub Bitbucket 1.4 BitbucketP Git FIzP Git Gi - 23

  • 3. Manage accountSSH keysSSH 1.13

    1.13n SSH P

    .x 1.11> cat/{P

    $ cat ~/.ssh/id_rsa.pub

    (CreateF 1.14pThis is a private repositoryFCreate repositoryFCommand line > I have an existing projectJ > dI 1.12I 1.12 eFAreyou sure you want to continue connecting (yes/no)?yes

    .x 1.12n Bitbucket,

    $ git remote add origin [email protected]:/hello_app.git

    $ git push -u origin --all # ,

    I Gite Bitbucketd"FF -uKgit set upstream1e ehJ

    $ git remote add origin [email protected]:mhartl/hello_app.git

    Bitbucket V hello_appFKM

  • 1.14 Bitbucket d,

    1.15 Bitbucket ,

    1.4. > Git Gi - 25

  • 1.4.4.^#

    e 1.4.3 z1Bitbucket F README.rdocMF README M 1.16 rdocK Bitbucket K)@g Markdown L README.rdocMREADME.mdm;.L Git gd

  • master

    * modify-README

    5J git branchd*gitcheckout -b modify-READMEJmodify-README1e 1.4 1 cog git co -b modify-README

    dNv12,d##m1K##VC`z

    mV&z"1e-

    #L README ML( RDoc Markdown M .mdBitbucket Vg Git iUnix mvJqM

    $ git mv README.rdoc README.md

    I 1.13 README.md

    .x 1.13 README1README.md

    # Ruby on Rails Tutorial: "hello, world!"

    This is the first application for the

    [*Ruby on Rails Tutorial*](http://www.railstutorial.org/)

    by [Michael Hartl](http://www.michaelhartl.com/).

    #

    $ git status

    On branch modify-README

    Changes to be committed:

    (use "git reset HEAD ..." to unstage)

    renamed: README.rdoc -> README.md

    Changes not staged for commit:

    (use "git add ..." to update what will be committed)

    (use "git checkout -- ..." to discard changes in working directory)

    modified: README.md

    LKg 1.4.1.2 git add -A\ git commiti1 -aK Git Gi - 27

  • $ git commit -a -m "Improve the README file"

    2 files changed, 5 insertions(+), 243 deletions(-)

    delete mode 100644 README.rdoc

    create mode 100644 README.md

    g -a1

  • $ git push

    Bitbucket g Markdown Mz1 1.17

    1.17> Markdown W README1

    1.5.

    gL)A& Rails =zzK(V13

    K Rails M4\Rails 1g Phusion PassengerApache Nginx 14 Web >#Engine Yard Rails Machinei]K Engine Yard CloudNinefoldHeroku7

    g Heroku Rails Heroku 6 Rails H Web Rails 1 Git ,"A& 1.4 C GitezzCaL Heroku ;d,

    13. e1K 1.5.4 z.Pb14. dEngine X

    1.5. - 29

  • 1.5.1. Heroku

    Heroku g PostgreSQL15 KL pg= Rails PostgreSQL p16

    group :production do

    gem 'pg', '0.17.1'

    gem 'rails_12factor', '0.0.2'

    end

    L1 rails_12factorHeroku g gem ZhGemfileI 1.14

    .x 1.14n gem Gemfile

    source 'https://rubygems.org'

    gem 'rails', '4.2.0'

    gem 'sass-rails', '5.0.0.beta1'

    gem 'uglifier', '2.5.3'

    gem 'coffee-rails', '4.1.0'

    gem 'jquery-rails', '4.0.0.beta2'

    gem 'turbolinks', '2.3.0'

    gem 'jbuilder', '2.2.3'

    gem 'sdoc', '0.4.0', group: :doc

    group :development, :test do

    gem 'sqlite3', '1.3.9'

    gem 'byebug', '3.4.0'

    gem 'web-console', '2.0.0.beta3'

    gem 'spring', '1.1.3'

    end

    group :production do

    gem 'pg', '0.17.1'

    gem 'rails_12factor', '0.0.2'

    end

    "1 bundle installJ=g gem pg rails_12factor

    $ bundle install --without production

    "LI 1.1416= gemKJVOa gem\J"L pg rails_12factor Gemfile.lock

  • L Heroku Heroku Heroku J

    $ heroku version

    g7 IDE V Heroku KgJ herokuHg Heroku Toolbelt

    Heroku J(g herokuJ SSH

    $ heroku login

    $ heroku keys:add

    heroku createJ Heroku M6I1.15

    .x 1.15 Heroku d

    $ heroku create

    Creating damp-fortress-5769... done, stack is cedar

    http://damp-fortress-5769.herokuapp.com/ | [email protected]:damp-fortress-5769.git

    Git remote heroku added

    herokuJV"e5L

    1.5.2. Heroku

    g Git # Heroku

    $ git push heroku master

    (V;7.5 V)

    1.5.3. Heroku

    51L1K heroku createJI1.157 IDEK heroku openJ 1.18 1.12\=

    1.5. - 31

  • 1.18 Heroku

    1.5.4. Heroku /

    Heroku i1J.C1CJd

    $ heroku rename rails-tutorial-hello

    eg11ezg Heroku ie6Kg;5h

    hwpcbmze.herokuapp.com

    seyjhflo.herokuapp.com

    jhyicevg.herokuapp.com

    g5e@HLeme Ruby 5I

    ('a'..'z').to_a.shuffle[0..7].join

    15Heroku '.17 Heroku e6 Heroku Heroku K6'pKHeroku H

    17. Heroku e Github Pages http://railstutorial-china.org

    32 - 1 +

  • 1.6.

    z14KVgL Rails 4

    e>.K Facebook [

    Ruby on Rails - Ruby on Railshttp://railstutorial-china.org/

    e Rails MKm.T

    1.6.1.h'

    Ruby on Rails g Ruby Web

    7 RailsKM

    Rails i1JJ rails6rails newrails server

    1dq1hello, world!

    "1,"1dL Git I

    Bitbucket F

    g Heroku =

    1.7.

    1. hellodI 1.8hello, world!hola, mundo!gshHola, mundo! Rails ASCII18 1.19

    2. hellodI 1.8d" goodbyegoodbye,world!qMI 1.10 goodbye 1.20

    18. eVinvalid multibyte charactereK

    1.6. - 33

  • 1.19D hellop=Hola, mundo!

    1.20Dgoodbye, world!

    34 - 1 +

  • 2 S

    L Rails LVg Ruby on Rails ,1 Web 1.2.SV"1,"1LK URL

  • group :production do

    gem 'pg', '0.17.1'

    gem 'rails_12factor', '0.0.2'

    end

    I 2.1I 1.14

    1.5.1 gem --without production= gem

    $ bundle install --without production

    Git

    $ git init

    $ git add -A

    $ git commit -m "Initialize repository"

    eK Bitbucket CreateF 2.1IF

    $ git remote add origin [email protected]:/toy_app.git

    $ git push -u origin --all # ,

    2.1 Bitbucket Sd,

    36 - 2 S

  • I 1.8I 1.91
  • 2.3.3 VCg user_id 11

    2.2.

    L 2.1.1 V" Web 5Users Resource"K HTTP cre-atereadupdatedeleteg Rails eIVe

    scaffoldW rails generateKg Rails 1W scaffold User3K;

    $ rails generate scaffold User name:string email:string

    invoke active_record

    create db/migrate/20140821011110_create_users.rb

    create app/models/user.rb

    invoke test_unit

    create test/models/user_test.rb

    create test/fixtures/users.yml

    invoke resource_route

    route resources :users

    invoke scaffold_controller

    create app/controllers/users_controller.rb

    invoke erb

    create app/views/users

    create app/views/users/index.html.erb

    create app/views/users/edit.html.erb

    create app/views/users/show.html.erb

    create app/views/users/new.html.erb

    create app/views/users/_form.html.erb

    invoke test_unit

    create test/controllers/users_controller_test.rb

    invoke helper

    create app/helpers/users_helper.rb

    invoke test_unit

    create test/helpers/users_helper_test.rb

    invoke jbuilder

    create app/views/users/index.json.jbuilder

    create app/views/users/show.json.jbuilder

    invoke assets

    invoke coffee

    create app/assets/javascripts/users.js.coffee

    invoke scss

    create app/assets/stylesheets/users.css.scss

    invoke scss

    create app/assets/stylesheets/scaffolds.css.scss

    3. ggg User Users

    38 - 2 S

  • LJ1 name:string email:stringK 2.21 idRails V"#primary key

    L Rake 2.1migrate

    $ bundle exec rake db:migrate

    == CreateUsers: migrating ==============================================

    -- create_table(:users)

    -> 0.0017s

    == CreateUsers: migrated (0.0018s) =====================================

    JVg'6.1.1 VC"1gGemfile Rake L bundle exec rake7 IDEg bundle exec\;gK"1JVg bundle exec

    J Web 1.74

    $ rails server -b $IP -p $PORT # `rails server`

    K11.3.2 g7 IDE IDE

    2.1Rake

    Unix make1`I=1M

    $ ./configure && make && sudo make install

    Unix Linux Mac OS XJI

    Rake Ruby make Ruby make Rails 1 Rake i16 Web Orake db:migrate(HJ rake -T dbKO

    $ bundle exec rake -T db

    Rake O

    $ bundle exec rake -T

    O@eJeVO

    2.2.1.Q

    URL http://localhost:3000/ Rails 1.9g1h /users /users/

    4. railsg bundle exec

    2.2. - 39

  • new;eV 2.11 URL (

    2.1 URL Q

    URL p= =

    /users index

    /users/1 show ID " 1

    /users/new new

    /users/1/edit edit ID " 1

    L 2.4

    2.4/users

    2.5http://localhost:30007 IDE V 7 V

    LKMCreate UserV 2.6flash message7.4.2 VC URL /users/1e1 1 2.2 id7.1 V

    40 - 2 S

  • 2.5/users/new

    2.6/users/1

    2.2. - 41

  • qp 2.7qpUpdate User1p 2.8 6 VCpLV 9.1 "p

    2.7C/users/1/edit

  • 2.8C

    2.9d/users

    2.2. - 43

  • 2.10f

    2.2.2. MVC

    L1LE MVC1.3.3 ;L1 MVC 2.11

    1. /users

    2. Rails /users

  • 2.11Rails MVC

    E 1 K,K Rails 2 URLK3.2d URL dII 2.2IV 2.1z:usersSymbol4.3.3VC

    .x 2.2Rails Rbconfig/routes.rb

    Rails.application.routes.draw do

    resources :users

    .

    .

    .

    end

    1M"q(V /usersI 1.10L

    2.2. - 45

  • # root 'welcome#index'

    1

    root 'application#hello'

    ApplicationController hellodLg UsersController indexdI 2.3q ApplicationController1 hellodd

    .x 2.3 UsersControllerp=config/routes.rb

    Rails.application.routes.draw do

    resources :users

    root 'users#index'

    .

    .

    .

    end

    2.2.1 6 UsersControllerdII 2.4 class UsersController < ApplicationController Ruby 2.3.4 VC4.4 zC

    .x 2.4i.app/controllers/users_controller.rb

    class UsersController < ApplicationController

    .

    .

    .

    def index

    .

    .

    .

    end

    def show

    .

    .

    .

    end

    def new

    .

    .

    .

    end

    def edit

    .

    .

    .

    46 - 2 S

  • end

    def create

    .

    .

    .

    end

    def update

    .

    .

    .

    end

    def destroy

    .

    .

    .

    end

    end

    e1dLindexshownew edit6 2.2.1 C;Hdcreateupdate destroy;d,VVqo 2.21d;d Rails REST 2.2REST Roy FieldingRepresentational State Transfer6 2.2 ;h show updated /users/1 5g HTTP 3.3 VC HTTP

    2.2.x 2.2 REST

    HTTP URL p= =

    GET /users index

    GET /users/1 show ID " 1

    GET /users/new new

    POST /users create

    GET /users/1/edit edit ID " 1

    PATCH /users/1 update ID " 1

    DELETE /users/1 destroy ID " 1

    6. 2000 Roy Thomas Fielding Architectural Styles and the Design of Network-based Software Ar-chitectures

    2.2. - 47

  • 2.2sREST

    e; Ruby on Rails Web V1RESTREpresentational State TransferREST 6Mh WWW Web REST Rails REST MhVresourceKcreatereadupdatedelete;d CRUD d HTTP POSTGETPATCH 7 DELETE3.3 3.2C HTTP

    d" Rails REST e;deKK1"L 12 g REST Km

    "1(L indexdI 2.5IKz1

    .x 2.5Ss indexp=app/controllers/users_controller.rb

    class UsersController < ApplicationController

    .

    .

    .

    def index

    @users = User.all

    end

    .

    .

    .

    end

    indexdI@users = User.all 2.11 3 E 4 v @usersdat-users 5 II2.6I[\1 2.3.4 4.4 ` Rails Active Record User.all

    .x 2.6Sapp/models/user.rb

    class User < ActiveRecord::Base

    end

    ' @users 6 II 2.7K @hinstance variablehindex.html.erbII2.7 @users" HTMLe;IeIA&

    7. Rails g PUT\ HTTP PATCH

    48 - 2 S

  • .x 2.7.app/views/users/index.html.erb

    Listing users

    Name

    Email

    I HTML 7 8

    2.2.3.

    e1 Rails\,;

    VM KOad ,V;,m

    H1

    eI.1

    2.3.y

    L1e 2.2 eVLK Rails REST (,#(

    2.3. y - 49

  • 2.3.1.y

    Lg rails generate scaffoldJI 2.38

    $ rails generate scaffold Micropost content:text user_id:integer

    invoke active_record

    create db/migrate/20140821012832_create_microposts.rb

    create app/models/micropost.rb

    invoke test_unit

    create test/models/micropost_test.rb

    create test/fixtures/microposts.yml

    invoke resource_route

    route resources :microposts

    invoke scaffold_controller

    create app/controllers/microposts_controller.rb

    invoke erb

    create app/views/microposts

    create app/views/microposts/index.html.erb

    create app/views/microposts/edit.html.erb

    create app/views/microposts/show.html.erb

    create app/views/microposts/new.html.erb

    create app/views/microposts/_form.html.erb

    invoke test_unit

    create test/controllers/microposts_controller_test.rb

    invoke helper

    create app/helpers/microposts_helper.rb

    invoke test_unit

    create test/helpers/microposts_helper_test.rb

    invoke jbuilder

    create app/views/microposts/index.json.jbuilder

    create app/views/microposts/show.json.jbuilder

    invoke assets

    invoke coffee

    create app/assets/javascripts/microposts.js.coffee

    invoke scss

    create app/assets/stylesheets/microposts.css.scss

    invoke scss

    identical app/assets/stylesheets/scaffolds.css.scss

    Spring J

    2.2 Lg

    $ bundle exec rake db:migrate

    == CreateMicroposts: migrating ===============================================

    -- create_table(:microposts)

    -> 0.0023s

    == CreateMicroposts: migrated (0.0026s) ======================================

    8. gJ,g generate Micropost

    50 - 2 S

  • LKg[ 2.2.1 C1e1V Rails M"I 2.89[resources :micropsts URL MicropostsController 2.3

    .x 2.8Rails ybconfig/routes.rb

    Rails.application.routes.draw do

    resources :microposts

    resources :users

    .

    .

    .

    end

    2.3.x 2.8y REST

    HTTP URL p= =

    GET /microposts index

    GET /microposts/1 show ID " 1

    GET /microposts/new new

    POST /microposts create

    GET /microposts/1/edit edit ID " 1

    PATCH /microposts/1 update ID " 1

    DELETE /microposts/1 destroy ID " 1

    MicropostsControllerII 2.91 UsersController Microp-ostsController(II 2.4A&1 REST (

    .x 2.9s MicropostsControllerapp/controllers/microposts_controller.rb

    class MicropostsController < ApplicationController

    .

    .

    .

    def index

    .

    .

    .

    end

    def show

    .

    9. II 2.8V" Ruby V

    2.3. y - 51

  • ..

    end

    def new

    .

    .

    .

    end

    def edit

    .

    .

    .

    end

    def create

    .

    .

    .

    end

    def update

    .

    .

    .

    end

    def destroy

    .

    .

    .

    end

    end

    L/microposts/new; 2.12

    1o user_id" 122.2.1 2.13[

    52 - 2 S

  • 2.12y

    2.13y/microposts

    2.3. y - 53

  • 2.3.2.iyT

    Rails gvalida-tion" 140 Twitter LKg IDE app/models/micropost.rbI 2.10I

    .x 2.10iy 140 app/models/micropost.rb

    class Micropost < ActiveRecord::Base

    validates :content, length: { maximum: 140 }

    end

    ILV 6.2 CL 140 d1 2.14Rails Vp17.3.3 VCp

    2.14y

    2.3.3.y

    Rails (K(associationhKLKI 2.11I2.12I

    .x 2.11yapp/models/user.rb

    54 - 2 S

  • class User < ActiveRecord::Base

    has_many :microposts

    end

    .x 2.12y app/models/micropost.rb

    class Micropost < ActiveRecord::Base

    belongs_to :user

    validates :content, length: { maximum: 140 }

    end

    LK 2.15" microposts user_idK Rails Active Record

    2.15yQ

    11 12 LVg(V Twitter[LKconsole( Rails > first_user = User.first

    => #

    >> first_user.microposts

    => [#, #]

    >> micropost = first_user.microposts.first # Micropost.first would also work.

    => #

    >> micropost.user

    => #

    >> exit

    I1 exitea,K Ctrl-D 11 Lg first_user.micropostsActive Record V user_id first_userID1 11 12 LV-

    10. eV[ 2.1.1 :001 >\hg >>I" Ruby 11. Ctrl-CCtrl-d\-Ctrl-D

    2.3. y - 55

  • 2.3.4.
  • class UsersController < ApplicationController

    .

    .

    .

    end

    .x 2.16MicropostsControllerapp/controllers/microposts_controller.rb

    class MicropostsController < ApplicationController

    .

    .

    .

    end

    .x 2.17ApplicationControllerapp/controllers/application_controller.rb

    class ApplicationController < ActionController::Base

    .

    .

    .

    end

    2.17UsersController MicropostsController

  • $ git commit -m "Finish toy app"

    $ git push

    ez;

  • C1 MVC `1 REST g1 =16 Web

    ' h6 ( ' z4z4

    .;T(V

    2.4.1.h'

    gI Web

  • class Micropost < ActiveRecord::Base

    belongs_to :user

    validates :content, length: { maximum: 140 },

    presence: true

    end

    .x 2.19nNapp/models/user.rb

    class User < ActiveRecord::Base

    has_many :microposts

    validates FILL_IN, presence: true

    validates FILL_IN, presence: true

    end

    2.19y

    60 - 2 S

  • 2.20

    2.5. - 61

  • 3

    EL.VKPLE[[M4',

    Rails "16,Og HTML g Rails e&zLVautomated testingKLpIMKLpIq\

    3.1.d

    2 L Rails " sample_appI 3.11

    .x 3.1d

    $ cd ~/workspace

    $ rails _4.2.0_ new sample_app

    $ cd sample_app/

    2.1 g7 IDEKdd

    [ 2.1 L Gemfile gemI 3.2I 1.5I 2.1 test gem Vz3.7 eg gemI 11.66

    .x 3.2 Gemfile

    source 'https://rubygems.org'

    gem 'rails', '4.2.0'

    gem 'sass-rails', '5.0.0.beta1'

    gem 'uglifier', '2.5.3'

    gem 'coffee-rails', '4.1.0'

    gem 'jquery-rails', '4.0.0.beta2'

    gem 'turbolinks', '2.3.0'

    gem 'jbuilder', '2.2.3'

    1. g7 IDEKgGoto AnythingJMmMMdMh"GemfileMV"MMGemfile Gemfile.lockeKworkspaceM rm -rf hello_app/ toy_app/J 1.1e(1 BitbucketK

    63

  • gem 'sdoc', '0.4.0', group: :doc

    group :development, :test do

    gem 'sqlite3', '1.3.9'

    gem 'byebug', '3.4.0'

    gem 'web-console', '2.0.0.beta3'

    gem 'spring', '1.1.3'

    end

    group :test do

    gem 'minitest-reporters', '1.0.5'

    gem 'mini_backtrace', '0.1.3'

    gem 'guard-minitest', '2.3.1'

    end

    group :production do

    gem 'pg', '0.17.1'

    gem 'rails_12factor', '0.0.2'

    end

    L bundle installJ Gemfile gem --withoutproduction2=g gem

    $ bundle install --without production

    JV PostgreSQL pg gem=LgSQLiteHeroku =g\A& SQLite PostgreSQL 3e(1 gemhRails H Gemfile bundle updateJ gemo

    $ bundle update

    L Git F

    $ git init

    $ git add -A

    $ git commit -m "Initialize repository"

    e READMEMLME RDoc " Markdown

    $ git mv README.rdoc README.md

    I 3.3

    2. V Bundler _ bundle install3. \eVa PostgreSQLKinstallconfigure postgresql Krails postgresql setup7 IDE Ubuntu

    64 - 3

  • .x 3.3D README1

    # Ruby on Rails Tutorial: sample application

    This is the sample application for the

    [*Ruby on Rails Tutorial:

    Learn Web Development with Rails*](http://www.railstutorial.org/)

    by [Michael Hartl](http://www.michaelhartl.com/).

  • JdoL6#6 master static-pagese#KJ

    3.2.1.

    Lg 2 generateJ" StaticPagesKgL6d" homehelp aboutgenerateJKdLJd\6d 3.3 C&dJI 3.4

    .x 3.4i

    $ rails generate controller StaticPages home help

    create app/controllers/static_pages_controller.rb

    route get 'static_pages/help'

    route get 'static_pages/home'

    invoke erb

    create app/views/static_pages

    create app/views/static_pages/home.html.erb

    create app/views/static_pages/help.html.erb

    invoke test_unit

    create test/controllers/static_pages_controller_test.rb

    invoke helper

    create app/helpers/static_pages_helper.rb

    invoke test_unit

    create test/helpers/static_pages_helper_test.rb

    invoke assets

    invoke coffee

    create app/assets/javascripts/static_pages.js.coffee

    invoke scss

    create app/assets/stylesheets/static_pages.css.scss

    mrails generateK rails g(Rails i1J3.1"1.VgJ\g Rails Vg

    3.1Rails "/W

    W

    $ rails server $ rails s

    $ rails console $ rails c

    $ rails generate $ rails g

    $ bundle install $ bundle

    $ rake test $ rake

    (eg GitMF

    66 - 3

  • $ git status

    $ git add -A

    $ git commit -m "Add a Static Pages controller"

    $ git push -u origin static-pages

    J static-pages# BitbucketKK

    $ git push

    V

  • $ bundle exec rake db:migrate

    LKgJd

    $ bundle exec rake db:rollback

    Kg

    $ bundle exec rake db:migrate VERSION=0

    e1 0 HV;

    ;LK1

    I 3.4JVqMconfig/routes.rbL 1.3.4 CMd URL ( 2.11M configMRails MM 3.1

    3.1 config1T

    "L1 home helpdKM1I 3.5

    .x 3.5i home helpp=config/routes.rb

    Rails.application.routes.draw do

    get 'static_pages/home'

    get 'static_pages/help'

    .

    68 - 3

  • ..

    end

    get 'static_pages/home'

    /static_pages/home homedget GETGET HTTPWHypertext Transfer Protocol(3.2hL homed /static_pages/home 1 1.3.2 Rails

    $ rails server -b $IP -p $PORT # `rails server`

    /static_pages/home 3.2

    3.2/static_pages/home

    3.2GET

    WHTTP'1dGETPOSTPATCH DELETE1h ChromeFirefox SafariV Web h Apache Nginx(de Rails \5 REST Web

    3.2. - 69

  • Rails HTTP L 2 C1 RESTE 7 VzC

    GET HTTP dehttp://www.google.com http://www.wikipedia.org GETPOST5de

  • .x 3.7app/views/static_pages/home.html.erb

    StaticPages#home

    Find me in app/views/static_pages/home.html.erb

    helpd[I 3.8

    .x 3.8qapp/views/static_pages/help.html.erb

    StaticPages#help

    Find me in app/views/static_pages/help.html.erb

    ]Lh1Mp

    3.2.2.DT

    LV 3.4 ;;"1M4Rails K HTMLKL1 Rails KqI 3.9 3.10

    .x 3.9D HTMLapp/views/static_pages/home.html.erb

    Sample App

    This is the home page for the

    Ruby on Rails Tutorial

    sample application.

    .x 3.10Dq HTMLapp/views/static_pages/help.html.erb

    Help

    Get help on the Ruby on Rails Tutorial at the

    Rails Tutorial help section.

    To get help on this sample app, see the

    Ruby on Rails Tutorial

    book.

    q( 3.3 3.4

    3.2. - 71

  • 3.3D

    3.4Dq

    72 - 3

  • 3.3.

    Lq16z.LMd5d"I\L"1VL6K-

    ) Rails -\`dTest-Driven Development TDD4TDD I.tg TDD TDD 3.3

    3.3'E

    aKa("A

    1. regression6;(1

    2. \p

    3. IKLKaHM

  • L# 6 7d
  • .x 3.12GREEN

    $ bundle exec rake test

    2 tests, 2 assertions, 0 failures, 0 errors, 0 skips

    MKGREEN 3.7.1 MiniTest Vm"1 Spring Rails 2 Ruby ,5Kg 3.7.3 Guard

    3.3.2.

    L 3.3TDD II"ggK,--L 3.3.3 3.4.3 6

    L"6I 3.11e&I3.13

    .x 3.13Q REDtest/controllers/static_pages_controller_test.rb

    require 'test_helper'

    class StaticPagesControllerTest < ActionController::TestCase

    test "should get home" do

    get :home

    assert_response :success

    end

    test "should get help" do

    get :help

    assert_response :success

    end

    test "should get about" do

    get :about

    assert_response :success

    end

    end

    ?"6homehelp1about

    6. rake testOV\V 3.7.1

    3.3. - 75

  • .x 3.14RED

    $ bundle exec rake test

    3 tests, 2 assertions, 0 failures, 1 errors, 0 skips

    3.3.3.

    1REDLGREEN,K6

    L7

    .x 3.15RED

    $ bundle exec rake test

    ActionController::UrlGenerationError:

    No route matches {:action=>"about", :controller=>"static_pages"}

    dLMI 3.5LKI 3.16

    .x 3.16n about REDconfig/routes.rb

    Rails.application.routes.draw do

    get 'static_pages/home'

    get 'static_pages/help'

    get 'static_pages/about'

    .

    .

    .

    end

    I? Rails /static_pages/about GET

  • class StaticPagesController < ApplicationController

    def home

    end

    def help

    end

    def about

    end

    end

    j1

    $ bundle exec rake test

    ActionView::MissingTemplate: Missing template static_pages/about

    Rails 3.2.1 homed home.html.erboapp/views/static_pagesMKLMM"about.html.erb

    MKMMMKgMMo](Kg Unix touchJ

    $ touch app/views/static_pages/about.html.erb

    touch#dMMqH\dMVg7 IDEM 1.3.1

    M about.html.erbM(I 3.19

    .x 3.19Q T GREENapp/views/static_pages/about.html.erb

    About

    The Ruby on Rails

    Tutorial is a

    book and

    screencast series

    to teach web development with

    Ruby on Rails.

    This is the sample application for the tutorial.

    rake testV1

    .x 3.20GREEN

    $ bundle exec rake test

    3 tests, 3 assertions, 0 failures, 0 errors, 0 skips

    LK 3.5KL

    3.3. - 77

  • 3.5nQ /static_pages/about

    3.3.4.

    1LKp1IVIVV\@VKI;4LA&IK 3.4.3

    3.4.pT

    L";1d;L3&z" 7

    Lq6"Lg VTSearch-Engine Optimization SEO,Lg--";gMV | Ruby on Rails Tutorial Sam-ple App 3.2

    rails newJVMLM

    $ mv app/views/layouts/application.html.erb layout_file # p

    78 - 3

  • e&zMed

    3.2T

    URL p^

    /static_pages/home "Ruby on Rails Tutorial Sample App" "Home"

    /static_pages/help "Ruby on Rails Tutorial Sample App" "Help"

    6 /static_pages/about "Ruby on Rails Tutorial Sample App" "About"

    3.4.1.

    (L-I 3.21

    .x 3.21 HTML

    Greeting

    Hello, world!

    Idocument type declaration doctypegHTML hg HTML58 head titleGreeting body pHello, world!HTMLVV\K

    Lg assert_select" 3.2I 3.13assert_selectd HTML ,EK9

    assert_select "title", "Home | Ruby on Rails Tutorial Sample App"

    Id K Home | Ruby on Rails TutorialSample AppII 3.22

    .x 3.22nNi REDtest/controllers/static_pages_controller_test.rb

    require 'test_helper'

    class StaticPagesControllerTest < ActionController::TestCase

    8. HTML doctype KoK" HTML HTML5 9. Rails C1 MiniTest

    3.4. pT - 79

  • test "should get home" do

    get :home

    assert_response :success

    assert_select "title", "Home | Ruby on Rails Tutorial Sample App"

    end

    test "should get help" do

    get :help

    assert_response :success

    assert_select "title", "Help | Ruby on Rails Tutorial Sample App"

    end

    test "should get about" do

    get :about

    assert_response :success

    assert_select "title", "About | Ruby on Rails Tutorial Sample App"

    end

    end

    egRuby on Rails Tutorial Sample AppK 3.6 -

    (MRED

    .x 3.23RED

    $ bundle exec rake test

    3 tests, 6 assertions, 3 failures, 0 errors, 0 skips

    3.4.2.n

    L"I 3.21 HTML I 3.9I 3.24

    .x 3.24S HTML REDapp/views/static_pages/home.html.erb

    Home | Ruby on Rails Tutorial Sample App

    Sample App

    This is the home page for the

    Ruby on Rails Tutorial

    sample application.

    q( 3.610

    80 - 3

  • 3.6n

    g[q6II 3.25I 3.26

    .x 3.25S HTML q REDapp/views/static_pages/help.html.erb

    Help | Ruby on Rails Tutorial Sample App

    Help

    Get help on the Ruby on Rails Tutorial at the

    Rails Tutorial help

    section.

    To get help on this sample app, see the

    Ruby on Rails

    Tutorial book.

    10. .g Google Chrome\g Safari" Chrome

    3.4. pT - 81

  • .x 3.26S HTML Q GREENapp/views/static_pages/about.html.erb

    About | Ruby on Rails Tutorial Sample App

    About

    The Ruby on Rails

    Tutorial is a

    book and

    screencast series

    to teach web development with

    Ruby on Rails.

    This is the sample application for the tutorial.

    M1GREEN

    .x 3.27GREEN

    $ bundle exec rake test

    3 tests, 6 assertions, 0 failures, 0 errors, 0 skips

    3.4.3.N Ruby

    "z14Lg Rails d1; HTML` Rails (I

    )\

    Ruby on Rails Tutorial Sample App

    HTML 1

    I1Dont Repeat Yourself DRY DRY ILD

    ;ILI1

    g RubyEmbedded Ruby6Lg Rails i provide home.html.erbHomeI 3.28ILKd

    .x 3.28>N Ruby . GREENapp/views/static_pages/home.html.erb

    82 - 3

  • | Ruby on Rails Tutorial Sample App

    Sample App

    This is the home page for the

    Ruby on Rails Tutorial

    sample application.

    ILg1 Ruby ERbe"A& HTML M .html.erb1ERb "#g11I

    Rails provide "Home" :title12Lg[ Ruby yield13

    | Ruby on Rails Tutorial Sample App

    Ruby I6I,VIVK ERb

    LKGREEN

    .x 3.29GREEN

    $ bundle exec rake test

    3 tests, 6 assertions, 0 failures, 0 errors, 0 skips

    qI 3.306I 3.31

    .x 3.30>N Ruby .q GREENapp/views/static_pages/help.html.erb

    | Ruby on Rails Tutorial Sample App

    11. Haml@g12. Rails g content_for Asset Pipeline provideI

    13. e RubyV Rails &,g Rails

    3.4. pT - 83

  • Help

    Get help on the Ruby on Rails Tutorial at the

    Rails Tutorial help

    section.

    To get help on this sample app, see the

    Ruby on Rails

    Tutorial book.

    .x 3.31>N Ruby .Q GREENapp/views/static_pages/about.html.erb

    | Ruby on Rails Tutorial Sample App

    About

    The Ruby on Rails

    Tutorial is a

    book and

    screencast series

    to teach web development with

    Ruby on Rails.

    This is the sample application for the tutorial.

    L1 ERb[

    | Ruby on Rails Tutorial Sample App

    Contents

    , title body;

    "1Rails i1M" application.html.erbL 3.4 1M

    84 - 3

  • $ mv layout_file app/views/layouts/application.html.erb

    gLIg Ruby

    | Ruby on Rails Tutorial Sample App

    qMI 3.32

    .x 3.32 GREENapp/views/layouts/application.html.erb

    | Ruby on Rails Tutorial Sample App

    true %>

    true %>

    Id1`LgI /static_pages/home V home.html.erb HTML ]

    Rails MI

    Id JavaScript MAsset Pipeline 5.2.1 VC

    Rails csrf_meta_tagsdXCross-Site Request Forgery CSRF

    I 3.283.30 3.31M[ HTML KLoI 3.333.34 3.35

    .x 3.33} HTML GREENapp/views/static_pages/home.html.erb

    Sample App

    This is the home page for the

    Ruby on Rails Tutorial

    3.4. pT - 85

  • sample application.

    .x 3.34} HTML q GREENapp/views/static_pages/help.html.erb

    Help

    Get help on the Ruby on Rails Tutorial at the

    Rails Tutorial help section.

    To get help on this sample app, see the

    Ruby on Rails Tutorial

    book.

    .x 3.35} HTML Q GREENapp/views/static_pages/about.html.erb

    About

    The Ruby on Rails

    Tutorial is a

    book and

    screencast series

    to teach web development with

    Ruby on Rails.

    This is the sample application for the tutorial.

    q6(\1

    Lm,KM1L\(1LM

    .x 3.36GREEN

    $ bundle exec rake test

    3 tests, 6 assertions, 0 failures, 0 errors, 0 skips

    I\i1K

    3.4.4.

    Lq1,1(L 1.3.4 2.2.2 zLq routes.rbM /LL 3.1 hellodEI 3.37L getI 3.5

    root 'static_pages#home'

    86 - 3

  • L static_pages/home static_pages#homeo GET /V
  • g 1.4.4 C#

    $ git checkout master

    $ git merge static-pages

    ;dIFe 1.4.3 z1F Bitbuck-et

    $ git push

    e Heroku

    $ bundle exec rake test

    $ git push heroku

    (LM-

    3.5.1.h'

    LCE Rails gemFK=

    rails generate controller ControllerName JV

    config/routes.rbM'1

    Rails K HTML Ruby IERb

    MLLpK

    g--

    Rails 'K

    3.6.

    EK#z-

    $ git checkout static-pages

    $ git checkout -b static-pages-exercises

    &zV.=1

    -zKFF

    # G$ git commit -am "Eliminate repetition (solves exercise 3.1)"

    # G$ git add -A

    $ git commit -m "Add a Contact page (solves exercise 3.2)"

    $ git push -u origin static-pages-exercises

    $ git checkout master

    "1#\K=g

  • 1. e1I 3.22;Ruby onRails Tutorial Sample AppLg setup(eI 3.38DI 3.38g1h2.2.2 C4.4.5 VCIg1 vd4.2.2 VzC

    2. "14I 3.13" Contact | Ruby on Rails Tutorial Sample AppE /static_pages/contact I 3.39-KI 3.39IVI 3.38

    .x 3.38>i GREENtest/controllers/static_pages_controller_test.rb

    require 'test_helper'

    class StaticPagesControllerTest < ActionController::TestCase

    def setup

    @base_title = "Ruby on Rails Tutorial Sample App"

    end

    test "should get home" do

    get :home

    assert_response :success

    assert_select "title", "Home | #{@base_title}"

    end

    test "should get help" do

    get :help

    assert_response :success

    assert_select "title", "Help | #{@base_title}"

    end

    test "should get about" do

    get :about

    assert_response :success

    assert_select "title", "About | #{@base_title}"

    end

    end

    .x 3.39Tapp/views/static_pages/contact.html.erb

    Contact

    Contact the Ruby on Rails Tutorial about the sample app at the

    contact page.

    14. -V 5.3.1

    3.6. - 89

  • 3.7.

    C.g3.7.13.7.2 M3.7.3 gI"1me

    #q

    $ git checkout master

    3.7.1. MiniTest

    "1 Rails eMI 3.4015I 3.2 minitest-reporters gem

    .x 3.40test/test_helper.rb

    ENV['RAILS_ENV'] ||= 'test'

    require File.expand_path('../../config/environment', __FILE__)

    require 'rails/test_help'

    require "minitest/reporters"

    Minitest::Reporters.use!

    class ActiveSupport::TestCase

    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical

    # order.

    fixtures :all

    # Add more helper methods to be used by all tests here...

    end

    q7 IDE 3.8

    3.8! IDE

    15. Ig1 g1 " rails newJMg MiniTest g Ruby I 4.2.2

    90 - 3

  • 3.7.2.

    VEI\;7 IDEVIKgem RailsIjM&

    LK"LgI 3.2 mini_backtrace gem7 IDE rvm Ruby Version Manag-erKgI 3.41;

    .x 3.41n RVM QTconfig/initializers/backtrace_silencers.rb

    # Be sure to restart your server when you modify this file.

    # You can add backtrace silencers for libraries that you're using but don't

    # wish to see in your backtraces.

    Rails.backtrace_cleaner.add_silencer { |line| line =~ /rvm/ }

    # You can also remove all the silencers if you're trying to debug a problem

    # that might stem from framework code.

    # Rails.backtrace_cleaner.remove_silencers!

    I

    3.7.3.> Guard p

    g rake testJ@J"1mLKg GuardGuard VMxeq1 stat-ic_pages_controller_test.rb& Guard VMLK Guard home.html.erbMq, static_pages_controller_test.rb

    I 3.21 guard gemKL

    $ bundle exec guard init

    Writing new Guardfile to /home/ubuntu/workspace/sample_app/Guardfile

    00:51:32 - INFO - minitest guard added to Guardfile, feel free to edit it

    GuardfileM Guard I3.42MK

    .x 3.42D Guardfile

    # Defines the matching rules for Guard.

    guard :minitest, spring: true, all_on_start: false do

    watch(%r{^test/(.*)/?(.*)_test\.rb$})

    watch('test/test_helper.rb') { 'test' }

    watch('config/routes.rb') { integration_tests }

    watch(%r{^app/models/(.*?)\.rb$}) do |matches|

    "test/models/#{matches[1]}_test.rb"

    end

    watch(%r{^app/controllers/(.*?)_controller\.rb$}) do |matches|

    3.7. - 91

  • resource_tests(matches[1])

    end

    watch(%r{^app/views/([^/]*?)/.*\.html\.erb$}) do |matches|

    ["test/controllers/#{matches[1]}_controller_test.rb"] +

    integration_tests(matches[1])

    end

    watch(%r{^app/helpers/(.*?)_helper\.rb$}) do |matches|

    integration_tests(matches[1])

    end

    watch('app/views/layouts/application.html.erb') do

    'test/integration/site_layout_test.rb'

    end

    watch('app/helpers/sessions_helper.rb') do

    integration_tests

  • g Guard "1 Spring Git spring/M .gitignoreM Git M7 IDE &z

    M 3.9

    Show hidden filesM .gitignoreM 3.10

    .gitignoreM 3.11I 3.43

    3.91

    3.7. - 93

  • 3.101

    3.11 .gitignore1[

    94 - 3

  • .x 3.43 Spring nh .gitignore1

    # See https://help.github.com/articles/ignoring-files for more about ignoring

    # files.

    #

    # If you find yourself ignoring temporary files generated by your text editor

    # or operating system, you probably want to add a global ignore instead:

    # git config --global core.excludesfile '~/.gitignore_global'

    # Ignore bundler config.

    /.bundle

    # Ignore the default SQLite database.

    /db/*.sqlite3

    /db/*.sqlite3-journal

    # Ignore all logfiles and tempfiles.

    /log/*.log

    /tmp

    # Ignore Spring files.

    /spring/*.pid

    d.Spring Spring Ve 3.4 Spring

    3.4Unix

    Unix h Linux OS XOprocessK psJ aux

    $ ps aux

    Kg Unix d| psJW grep

    $ ps aux | grep spring

    ubuntu 12241 0.3 0.5 589960 178416 ? Ssl Sep20 1:46

    spring app | sample_app | started 7 hours ago

    p ID pidKg killJ pid kill p 9

    $ kill -9 12241

    hg Rails ps aux | grep serverJ pidghspring Springg springJ

    $ spring stop

    &z&Kg pkillJ"spring

    3.7. - 95

  • $ pkill -9 -f spring

    1 ps auxJ&4 kill -9 pkill -9 -f J

    Guard ( 1.3.2 Rails zJ

    $ bundle exec guard

    I 3.42.z1ThqV guard>V Spring

    Guard Ctrl-D " Guard HI 3.42Guard M

    96 - 3

  • 4 Rails Ruby

    1 3 hzC; Rails Ruby Ruby Rails L6 Ruby -e Ruby e Rails Ruby ,V

    4.1.

    Eg Ruby L,K Rails KLj6.iIpM\LKLRuby

    Lq1)Lg Rails LgI 4.1I 3.32

    .x 4.1app/views/layouts/application.html.erb

    | Ruby on Rails Tutorial Sample App

    true %>

    true %>

    LI

    true %>

    Ig Rails stylesheet_link_tagp Rails API C application.css Rails I\ Ruby Ve Rails VC

    Rails 1iiLg(L''helper"1a'LI 4.1

    | Ruby on Rails Tutorial Sample App

    97

  • Ig provide'h

    Sample App

    This is the home page for the

    Ruby on Rails Tutorial

    sample application.

    &LiV`;KL11 provide,i&V

    | Ruby on Rails Tutorial Sample App

    \1

    "1L'" full_title'full_titleRuby on Rails Tutorial Sample App'1I 4.21

    .x 4.2 full_titleqapp/helpers/application_helper.rb

    module ApplicationHelper

    # def full_title(page_title = '')

    base_title = "Ruby on Rails Tutorial Sample App"

    if page_title.empty?

    base_title

    else

    "#{page_title} | #{base_title}"

    end

    end

    end

    '1LK

    | Ruby on Rails Tutorial Sample App

    I 4.3

    .x 4.3> full_titleq GREENapp/views/layouts/application.html.erb

    1. Mh" app/helper/static_pages_helper.rbhLg full_titleKM app/helper/application_helper.rb

    98 - 4 Rails Ruby

  • true %>

    true %>

    "1dLHomeoLqII 4.4 "Home"ez1-I 3.38q1' @base_title setup

    .x 4.4D REDtest/controllers/static_pages_controller_test.rb

    require 'test_helper'

    class StaticPagesControllerTest < ActionController::TestCase

    test "should get home" do

    get :home

    assert_response :success

    assert_select "title", "Ruby on Rails Tutorial Sample App"

    end

    test "should get help" do

    get :help

    assert_response :success

    assert_select "title", "Help | Ruby on Rails Tutorial Sample App"

    end

    test "should get about" do

    get :about

    assert_response :success

    assert_select "title", "About | Ruby on Rails Tutorial Sample App"

    end

    end

    LM

    .x 4.5RED

    $ bundle exec rake test

    3 tests, 6 assertions, 1 failures, 0 errors, 0 skips

    "1L provideI 4.6

    .x 4.6 GREENapp/views/static_pages/home.html.erb

    4.1. - 99

  • Sample App

    This is the home page for the

    Ruby on Rails Tutorial

    sample application.

    K1

    .x 4.7GREEN

    $ bundle exec rake test

    ( rake test1"1EKV;

    II 4.2 Rails ,\ Ruby 'vv vvVC;

    4.2.

    L- Ruby #g Rails Rails >

    Rails '(=7.1.1 VC

    -eKe)VOa1K Ctrl-C d Ctrl-D

    2. J Ctrl-W ooM Ctrl-E nano

    100 - 4 Rails Ruby

  • eV Ruby APIAPI p1h1Ruby K String

    4.2.1.

    Ruby K: #,RubyV\@,II

    # def full_title(page_title = '')

    .

    .

    .

    end

    d

    "1IdVh

    $ rails console

    >> 17 + 42 # n=> 59

    JeKV

    4.2.2.

    Web "E L`

    $ rails console

    >> "" # => ""

    >> "foo" # => "foo"

    ; g"h

    LKg +

    >> "foo" + "bar" # => "foobar"

    "foo" "bar" "foobar"3

    #{}vd4

    3. 6foobarKfoobarFUBAR Jargon File Cfoo4. Perl PHP @Kvh "foo $bar"

    4.2. - 101

  • >> first_name = "Michael" # F=> "Michael"

    >> "#{first_name} Hartl" # F=> "Michael Hartl"

    L "Michael"v first_name "#{first_name} Hartl"L,K v

    >> first_name = "Michael"

    => "Michael"

    >> last_name = "Hartl"

    => "Hartl"

    >> first_name + " " + last_name # n=> "Michael Hartl"

    >> "#{first_name} #{last_name}" # =F=> "Michael Hartl"

    dw6gv " "

    {

    Ruby putsdput ess

    >> puts "foo" # {foo

    => nil

    putsdputs "foo" vnil Ruby vA&"1V nil

    EhKputsV \n[ printV

    >> print "foo" # { puts =9nfoo=> nil

    >> print "foo\n" # puts "foo" foo

    => nil

    x

    Chg Ruby ,

    >> 'foo' # xd=> "foo"

    >> 'foo' + 'bar'

    => "foobar"

    (Ruby V vd

    >> '#{foo} bar' # xF==> "\#{foo} bar"

    102 - 4 Rails Ruby

  • g'h #

    Kzz4v& 'A& 6Lvehh\ng

    >> '\n' # n F=> "\\n"

    #Ruby g' gh14\'d1

    >> 'Newlines (\n) and tabs (\t) both use the backslash character \.'

    => "Newlines (\\n) and tabs (\\t) both use the backslash character \\."

    K8gL Ruby

    4.2.3.6

    Ruby nilLV 4.4.2 C'.e;h

    dh K length

    >> "foobar".length # length 6=> 6

    W'5 K empty?

    >> "foobar".empty?

    => false

    >> "".empty?

    => true

    empty? Ruby vv true falsev

    >> s = "foobar"

    >> if s.empty?

    >> "The string is empty"

    >> else

    >> "The string is nonempty"

    >> end

    => "The string is nonempty"

    Kg elsifelse + if

    5. ( Ruby 5,"

    4.2. - 103

  • >> if s.nil?

    >> "The variable is nil"

    >> elsif s.empty?

    >> "The string is empty"

    >> elsif s.include?("foo")

    >> "The string includes 'foo'"

    >> end

    => "The string includes 'foo'"

    vKg &&|| !dg

    >> x = "foo"

    => "foo"

    >> y = ""

    => ""

    >> puts "Both strings are empty" if x.empty? && y.empty?

    => nil

    >> puts "One of the strings is empty" if x.empty? || y.empty?

    "One of the strings is empty"

    => nil

    >> puts "x is not empty" if !x.empty?

    "x is not empty"

    => nil

    " Ruby & nil,K,K$hto_sKOa

    >> nil.to_s

    => ""

    LK chain

    >> nil.empty?

    NoMethodError: undefined method `empty?' for nil:NilClass

    >> nil.to_s.empty? # => true

    Lnil empty?\ nil.to_sK

    K"e

    >> "foo".nil?

    => false

    >> "".nil?

    => false

    >> nil.nil?

    => true

    I

    puts "x is not empty" if !x.empty?

    1 ifeK if"v unless,K&

    104 - 4 Rails Ruby

  • >> string = "foobar"

    >> puts "The string '#{string}' is nonempty." unless string.empty?

    The string 'foobar' is nonempty.

    => nil

    L nil1 false( Ruby v"xLKg !!dbang bangzdv

    >> !!nil

    => false

    (H Ruby v 0 ,

    >> !!0

    => true

    4.2.4.

    LK' homedI 3.6 full_titleI 4.2''LVM'"1hL'" string_messagev6"

    >> def string_message(str = '')

    >> if str.empty?

    >> "It's an empty string!"

    >> else

    >> "The string is nonempty."

    >> end

    >> end

    => :string_message

    >> puts string_message("foobar")

    The string is nonempty.

    >> puts string_message("")

    It's an empty string!

    >> puts string_message

    It's an empty string!

    JKK" def string_message(str ='')i1v Kstrgv

    Ruby vvv `6 str" Ruby ,KvN

    >> def string_message(str = '')

    >> return "It's an empty string!" if str.empty?

    >> return "The string is nonempty."

    >> end

    Vg5 returnreturn "The string is nonempty."Vd"v return

    4.2. - 105

  • A&'K strOh the_function_argument\d

    >> def string_message(the_function_argument = '')

    >> if the_function_argument.empty?

    >> "It's an empty string!"

    >> else

    >> "The string is nonempty."

    >> end

    >> end

    => nil

    >> puts string_message("")

    It's an empty string!

    >> puts string_message("foobar")

    The string is nonempty.

    4.2.5.q

    LI 4.2 full_title6(I 4.9

    .x 4.9 full_titleapp/helpers/application_helper.rb

    module ApplicationHelper

    # # def full_title(page_title = '') # ~base_title = "Ruby on Rails Tutorial Sample App" # Fif page_title.empty? # base_title # F

    else

    "#{page_title} | #{base_title}" # Fend

    end

    end

    'v v'1Kgmodule ApplicationHelper"Li1LKg includeH Ruby e'\V Rails "Lfull_titleg

    4.3.R-

    Web \,H C; Rails H Ruby

    6. L Rails &; URL d full_titleKgeK1g Rails 1 Rails d1 Rails Obie Fernandez The Rails 4 Way

    106 - 4 Rails Ruby

  • 4.3.1.F

    4.3.3 ,6 Rails h 2.3.3 has_many11.1.3 VzC

    L1 E KE split

    >> "foo bar baz".split # ^L=> ["foo", "bar", "baz"]

    d split ,K)Oa

    >> "fooxbarxbazx".split('x')

    => ["foo", "bar", "baz"]

    -Ruby ,E 05 1j

    >> a = [42, 8, 17]

    => [42, 8, 17]

    >> a[0] # Ruby >L=> 42

    >> a[1]

    => 8

    >> a[2]

    => 17

    >> a[-1] # 0=> 17

    LRuby g1(Ruby ";i17

    >> a # a F'=> [42, 8, 17]

    >> a.first

    => 42

    >> a.second

    => 8

    >> a.last

    => 17

    >> a.last == a[-1] # == => true

    1d ==Ruby Hi1 !=Hd

    >> x = a.length # 0 length => 3

    >> x == 3

    => true

    7. Ig second Ruby ' Rails Kg"Rails V Rails Ruby

    4.3. R- - 107

  • >> x == 1

    => false

    >> x != 1

    => true

    >> x >= 1

    => true

    >> x < 1

    => false

    1 lengthI(KH

    >> a

    => [42, 8, 17]

    >> a.empty?

    => false

    >> a.include?(42)

    => true

    >> a.sort

    => [8, 17, 42]

    >> a.reverse

    => [17, 8, 42]

    >> a.shuffle

    => [17, 42, 8]

    >> a

    => [42, 8, 17]

    q avqvgbang(K&"dbang

    >> a

    => [42, 8, 17]

    >> a.sort!

    => [8, 17, 42]

    >> a

    => [8, 17, 42]

    Kg pushgN a.push(6) # 6 nh=> [42, 8, 17, 6]

    >> a [42, 8, 17, 6, 7]

    >> a > a

    => [42, 8, 17, 7, "foo", "bar"]

    >> a.join # => "428177foobar"

    108 - 4 Rails Ruby

  • >> a.join(', ') # => "42, 8, 17, 7, foo, bar"

    [vrangeg to_a

    >> 0..9

    => 0..9

    >> 0..9.to_a # to_a 9 NoMethodError: undefined method `to_a' for 9:Fixnum

    >> (0..9).to_a # to_a r;F=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    0..9v5L

    v

    >> a = %w[foo bar baz quux] # %w dL=> ["foo", "bar", "baz", "quux"]

    >> a[0..2]

    => ["foo", "bar", "baz"]

    vvg -1 Ev

    >> a = (0..9).to_a

    => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    >> a[2..(a.length-1)] # >=> [2, 3, 4, 5, 6, 7, 8, 9]

    >> a[2..-1] # > -1=> [2, 3, 4, 5, 6, 7, 8, 9]

    v,Kg

    >> ('a'..'e').to_a

    => ["a", "b", "c", "d", "e"]

    4.3.2.

    vKKblock Ruby ,

    >> (1..5).each { |i| puts 2 * i }

    2

    4

    6

    8

    10

    => 1..5

    Iv (1..5) each { |i| puts 2 * i }W each|i| Ruby 'ahv eachV ieachVvvWI

    (

    4.3. R- - 109

  • >> (1..5).each do |i|

    ?> puts 2 * i

    >> end

    2

    4

    6

    8

    10

    => 1..5

    K66.IgIg do..end

    >> (1..5).each do |number|

    ?> puts 2 * number

    >> puts '-'

    >> end

    2

    -

    4

    -

    6

    -

    8

    -

    10

    -

    => 1..5

    I numberI1 ieKgOav

    e1;ez1V-8@Eh;h1 map

    >> 3.times { puts "Betelgeuse!" } # 3.times "Betelgeuse!"

    "Betelgeuse!"

    "Betelgeuse!"

    => 3

    >> (1..5).map { |i| i**2 } # ** => [1, 4, 9, 16, 25]

    >> %w[a b c] # V%w dL=> ["a", "b", "c"]

    >> %w[a b c].map { |char| char.upcase }

    => ["A", "B", "C"]

    >> %w[A B C].map { |char| char.downcase }

    => ["a", "b", "c"]

    KmapvIJmapdg

    8. closure@V;1;

    110 - 4 Rails Ruby

  • >> %w[A B C].map { |char| char.downcase }

    => ["a", "b", "c"]

    >> %w[A B C].map(&:downcase)

    => ["a", "b", "c"]

    14.3.3 VC Rails\@L1 Ruby I

    ghLI 4.4h

    test "should get home" do

    get :home

    assert_response :success

    assert_select "title", "Ruby on Rails Tutorial Sample App"

    end

    ,E doK#`test MV

    L 1.5.4 5g Ruby I

    ('a'..'z').to_a.shuffle[0..7].join

    L

    >> ('a'..'z').to_a # O=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",

    "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

    >> ('a'..'z').to_a.shuffle # => ["c", "g", "l", "k", "h", "z", "s", "i", "n", "d", "y", "u", "t", "j", "q",

    "b", "r", "o", "f", "e", "w", "v", "m", "a", "x", "p"]

    >> ('a'..'z').to_a.shuffle[0..7] # [k 8 L=> ["f", "w", "i", "a", "h", "p", "c", "x"]

    >> ('a'..'z').to_a.shuffle[0..7].join # [L=> "mznpybuj"

    4.3.3.

    Hash6g;Perl"z)KgOahKg

    >> user = {} # {} => {}

    >> user["first_name"] = "Michael" # "first_name"F "Michael"=> "Michael"

    >> user["last_name"] = "Hartl" # "last_name"F "Hartl"=> "Hartl"

    >> user["first_name"] # L8=> "Michael"

    >> user # => {"last_name"=>"Hartl", "first_name"=>"Michael"}

    4.3. R- - 111

  • ;vv{}Ve[\59g

    'gv'

    >> user = { "first_name" => "Michael", "last_name" => "Hartl" }

    => {"last_name"=>"Hartl", "first_name"=>"Michael"}

    I1 Ruby 1V;"A&;n Ruby =1

    "g Rails Symbol h:nameeK 10

    >> "name".split('')

    => ["n", "a", "m", "e"]

    >> :name.split('')

    NoMethodError: undefined method `split' for :name:Symbol

    >> "foobar".reverse

    => "raboof"

    >> :foobar.reverse

    NoMethodError: undefined method `reverse' for :foobar:Symbol

    Ruby H Rails KeV- g

    >> :foo-bar

    NameError: undefined local variable or method `bar' for main:Object

    >> :2foo

    SyntaxError

    Kg4

    LK' user

    >> user = { :name => "Michael Hartl", :email => "[email protected]" }

    => {:name=>"Michael Hartl", :email=>"[email protected]"}

    >> user[:name] # :name F=> "Michael Hartl"

    >> user[:password] # F=> nil

    EhK'v nil

    9. Ruby 1.9 KVoj10. g"f

    112 - 4 Rails Ruby

  • "1Ruby 1.9 "'1

    >> h1 = { :name => "Michael Hartl", :email => "[email protected]" }

    => {:name=>"Michael Hartl", :email=>"[email protected]"}

    >> h2 = { name: "Michael Hartl", email: "[email protected]" }

    => {:name=>"Michael Hartl", :email=>"[email protected]"}

    >> h1 == h2

    => true

    5 1:

    { name: "Michael Hartl", email: "[email protected]" }

    1Hh JavaScript Rails ,gKeL@" :name\ name:':name name:d{ :name "Michael Hartl" } { name: "Michael Hartl" }g :name

    vKOaI 4.10

    .x 4.10

    >> params = {} # paramsparameters => {}

    >> params[:user] = { name: "Michael Hartl", email: "[email protected]" }

    => {:name=>"Michael Hartl", :email=>"[email protected]"}

    >> params

    => {:user=>{:name=>"Michael Hartl", :email=>"[email protected]"}}

    >> params[:user][:email]

    => "[email protected]"

    Rails g"LE 7.3 V

    v, eachh" flashM:success :danger

    >> flash = { success: "It worked!", danger: "It failed." }

    => {:success=>"It worked!", :danger=>"It failed."}

    >> flash.each do |key, value|

    ?> puts "Key #{key.inspect} has value #{value.inspect}"

    >> end

    Key :success has value "It worked!"

    Key :danger has value "It failed."

    each eachvK eachVKv"]

    I1 inspect

    >> puts (1..5).to_a # F1

    2

    3

    4

    4.3. R- - 113

  • 5>> puts (1..5).to_a.inspect # [[1, 2, 3, 4, 5]

    >> puts :name, :name.inspect

    name

    :name

    >> puts "It worked!", "It worked!".inspect

    It worked!

    "It worked!"

    m"g inspectg"p11

    >> p :name # 2 'puts :name.inspect':name

    4.3.4.N CSS .

    LI 4.1I

    true %>

    LKI1 4.1 Rails '1I

    stylesheet_link_tag 'application', media: 'all',

    'data-turbolinks-track' => true

    1 Ruby KKN

    # ]0stylesheet_link_tag('application', media: 'all',

    'data-turbolinks-track' => true)

    stylesheet_link_tag 'application', media: 'all',

    'data-turbolinks-track' => true

    5media\&KKN

    # ~0stylesheet_link_tag 'application', { media: 'all',

    'data-turbolinks-track' => true }

    stylesheet_link_tag 'application', media: 'all',

    'data-turbolinks-track' => true

    "A& data-turbolinks-trackvgg

    data-turbolinks-track: true

    "4.3.3 gKg

    11. ;p puts nil Katarzyna Siwek

    114 - 4 Rails Ruby

  • 'data-turbolinks-track' => true

    "A&1 Ruby

    stylesheet_link_tag 'application', media: 'all',

    'data-turbolinks-track' => true

    "Ruby 12(KIoI 80 13

    KI

    stylesheet_link_tag 'application', media: 'all',

    'data-turbolinks-track' => true

    1 stylesheet_link_tagW C5 Rails 4.0 Turbolink"g V ERb VHTMLI 4.11eV CSS Mh ?body=1 Rails oq CSS V

    .x 4.11N CSS . HTML

    http://localhost:3000/assets/application.css CSS VM\; 5 VCa

    4.4. Ruby

    L(Ruby L';Ruby HgheObject-Oriented Program-ming OOP;[.L;h

    4.4.1.

    LghzhLg

    >> s = "foobar" # >=> "foobar"

    >> s.class

    => String

    L K classv

    12. I \n13. VeKi1h 1.5VKeI 80 K7 IDE Vg TextMateKView > Wrap Column > 78 Sublime Text View > Ruler > 78View > Ruler > 80

    4.4. Ruby - 115

  • 1g(LKgNnamed constructornew14

    >> s = String.new("foobar") # S=> "foobar"

    >> s.class

    => String

    >> s == "foobar"

    => true

    IgNL

    [

    >> a = Array.new([1, 3, 2])

    => [1, 3, 2]

    1 Array.newvHash.newvv

    >> h = Hash.new

    => {}

    >> h[:foo] # :foo F=> nil

    >> h = Hash.new(0) # 0 nil=> {}

    >> h[:foo]

    => 0

    h newclass method new,zhinstancehh lengthhinstance method

    4.4.2.

    -VLKg superclass

    >> s = String.new("foobar")

    => "foobar"

    >> s.class # s => String

    >> s.class.superclass # String => Object

    >> s.class.superclass.superclass # Ruby 1.9 > BasicObject ==> BasicObject

    >> s.class.superclass.superclass.superclass

    => nil

    4.1KString ObjectObject BasicObject\ Basi-cObject1 Ruby V

    14. v6 Ruby hxeg Ruby 1.9.3 K

    116 - 4 Rails Ruby

  • Ruby BasicObjectRuby '

    4.1StringQ

    L'" Word"palindrome? true

    >> class Word

    >> def palindrome?(string)

    >> string == string.reverse

    >> end

    >> end

    => :palindrome?

    LKg

    >> w = Word.new # d Word => #

    >> w.palindrome?("foobar")

    => false

    >> w.palindrome?("level")

    => true

    ehz1' d"&z Word String1I 4.12eI( Word'

    .x 4.12i Word

    >> class Word < String # Word String>> # true>> def palindrome?

    >> self == self.reverse # self .>> end

    >> end

    => nil

    4.4. Ruby - 117

  • Word < String Ruby 3.2 C1' palindrome?(Word

    >> s = Word.new("level") # d Word ?eF "level"=> "level"

    >> s.palindrome? # Word ?0 palindrome? => true

    >> s.length # Word ?=> 5

    Word StringLK

    >> s.class

    => Word

    >> s.class.superclass

    => String

    >> s.class.superclass.superclass

    => Object

    4.2

    4.2.x 4.12 WordTQ

    I 4.12 Word Ruby gself15 WordselfIKLKg

    self == self.reverse

    "K self.vK,K self == reverse

    15. 6 Ruby self RailsTipsClass and Instance Variables in Ruby

    118 - 4 Rails Ruby

  • 4.4.3.DT

    h palindrome? String11HLK palindrome?L

    >> "level".palindrome?

    NoMethodError: undefined method `palindrome?' for "level":String

    J@Ruby e&zRuby KqL@;

    >> class String

    >> # true>> def palindrome?

    >> self == self.reverse

    >> end

    >> end

    => nil

    >> "deified".palindrome?

    => true

    Ruby "deified"

    qO,-Rails h Web Lvblank(K Rails " Ruby 1 blank?Rails V Rails h irbK

    >> "".blank?

    => true

    >> " ".empty?

    => false

    >> " ".blank?

    => true

    >> nil.blank?

    => true

    K emptyblanknil," nil KI1 Rails blank? String Object8.4VC; Rails Ruby h

    4.4.4.i

    e[L(I 3.18

    class StaticPagesController < ApplicationController

    def home

    end

    def help

    end

    4.4. Ruby - 119

  • def about

    end

    end

    eK;I1StaticPagesController Applica-tionController homehelp about" Rails V Rails KLK16

    >> controller = StaticPagesController.new

    => #

    >> controller.class

    => StaticPagesController

    >> controller.class.superclass

    => ApplicationController

    >> controller.class.superclass.superclass

    => ActionController::Base

    >> controller.class.superclass.superclass.superclass

    => ActionController::Metal

    >> controller.class.superclass.superclass.superclass.superclass

    => AbstractController::Base

    >> controller.class.superclass.superclass.superclass.superclass.superclass

    => Object

    4.3

    LKdd

    >> controller.home

    => nil

    homedv" nil"

    dvvL 3 homedv\Oa StaticPagesController.new&4

    6Rails Ruby \ Rails Ruby; Rails Ruby ,;6 Rails Rails Ruby -

    16. ed,LA&E 2005 g Ruby on Rai