Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
IntheprocessoftakingabrieftourofRubyinChapter4,welearnedaboutincludingtheapplicationstylesheetintothe
sampleapplication(Section4.1),but(asnotedinSection4.3.4)thestylesheetdoesntyetcontainanyCSS. Inthis
chapter,wellstartfillinginthecustomstylesheetbyincorporatingaCSSframeworkintoourapplication,andthenwell
addsomecustomstylesofourown.1 Wellalsostartfillinginthelayoutwithlinkstothepages(suchasHomeand
About)thatwevecreatedsofar(Section5.1). Alongtheway,welllearnaboutpartials,Railsroutes,andtheasset
pipeline,includinganintroductiontoSass(Section5.2). Wellendbytakingafirstimportantsteptowardlettingusers
signuptooursite(Section5.4).
Mostofthechangesinthischapterinvolveaddingandeditingmarkupinthesampleapplicationssitelayout,which
(basedontheguidelinesinBox3.3)isexactlythekindofworkthatwewouldntordinarilytestdrive,oreventestat
all. Asaresult,wellspendmostofourtimeinourtexteditorandbrowser,usingTDDonlytoaddaContactpage
(Section5.3.1). Wewilladdanimportantnewtest,though,writingourfirstintegrationtesttocheckthatthelinksonthe
finallayoutarecorrect(Section5.3.4).
5.1 Addingsomestructure
TheRubyonRailsTutorialisabookonwebdevelopment,notwebdesign,butitwouldbedepressingtoworkonan
applicationthatlookslikecompletecrap,sointhissectionwelladdsomestructuretothelayoutandgiveitsome
minimalstylingwithCSS. InadditiontousingsomecustomCSSrules,wellmakeuseofBootstrap,anopensourceweb
designframeworkfromTwitter. Wellalsogiveourcodesomestyling,sotospeak,usingpartialstotidyupthelayout
onceitgetsalittlecluttered.
Whenbuildingwebapplications,itisoftenusefultogetahighleveloverviewoftheuserinterfaceasearlyas
possible. Throughouttherestofthisbook,Iwillthusoftenincludemockups(inawebcontextoftencalledwireframes),
whichareroughsketchesofwhattheeventualapplicationwilllooklike.2 Inthischapter,wewillprincipallybe
developingthestaticpagesintroducedinSection3.2,includingasitelogo,anavigationheader,andasitefooter. A
mockupforthemostimportantofthesepages,theHomepage,appearsinFigure5.1. Youcanseethefinalresult
inFigure5.9. Youllnotethatitdiffersinsomedetailsforexample,wellendupaddingaRailslogoonthepagebut
thatsfine,sinceamockupneednotbeexact.
Figure5.1: AmockupofthesampleapplicationsHomepage.
Asusual,ifyoureusingGitforversioncontrol,nowwouldbeagoodtimetomakeanewbranch:
$ git checkout -b filling-in-layout
5.1.1 Sitenavigation
Asafirststeptowardaddinglinksandstylestothesampleapplication,wellupdatethesitelayout
fileapplication.html.erb(lastseeninListing4.3)withadditionalHTMLstructure. Thisincludessomeadditional
divisions,someCSSclasses,andthestartofoursitenavigation. ThefullfileisinListing5.1explanationsforthevarious
piecesfollowimmediatelythereafter. Ifyoudrathernotdelaygratification,youcanseetheresultsinFigure5.2. (Note:
itsnot(yet)verygratifying.)
Listing5.1: Thesitelayoutwithaddedstructure.
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag
'application', media: 'all',
'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js">
</script>
<![endif]-->
</head>
<body>
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<%= link_to "sample app", '#', id: "logo" %>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", '#' %></li>
<li><%= link_to "Help", '#' %></li>
LetslookatthenewelementsinListing5.1fromtoptobottom. AsalludedtobrieflyinSection3.4.1,RailsusesHTML5
bydefault(asindicatedbythedoctype<!DOCTYPE html>)sincetheHTML5standardisrelativelynew,somebrowsers
(especiallyolderversionsofInternetExplorer)dontfullysupportit,soweincludesomeJavaScriptcode(knownasan
HTML5shim(orshiv))3 toworkaroundtheissue:
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js">
</script>
<![endif]-->
Thesomewhatoddsyntax
<!--[if lt IE 9]>
Heretheheadertagindicateselementsthatshouldgoatthetopofthepage. WevegiventheheadertagthreeCSS
classes,4 callednavbar,navbar-fixed-top,andnavbar-inverse,separatedbyspaces:
<header class="navbar navbar-fixed-top navbar-inverse">
AllHTMLelementscanbeassignedbothclassesandidsthesearemerelylabels,andareusefulforstylingwithCSS
(Section5.1.2). Themaindifferencebetweenclassesandidsisthatclassescanbeusedmultipletimesonapage,butids
canbeusedonlyonce. Inthepresentcase,allthenavbarclasseshavespecialmeaningtotheBootstrapframework,
whichwellinstallanduseinSection5.1.2.
Insidetheheadertag,weseeadivtag:
<div class="container">
Thedivtagisagenericdivisionitdoesntdoanythingapartfromdividethedocumentintodistinctparts. Inolderstyle
HTML,divtagsareusedfornearlyallsitedivisions,butHTML5addstheheader,nav,andsectionelementsfor
divisionscommontomanyapplications. Inthiscase,thedivhasaCSSclassaswell(container). Aswith
theheadertagsclasses,thisclasshasspecialmeaningtoBootstrap.
Afterthediv,weencountersomeembeddedRuby:
<%= link_to "sample app", '#', id: "logo" %>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", '#' %></li>
<li><%= link_to "Help", '#' %></li>
<li><%= link_to "Log in", '#' %></li>
</ul>
</nav>
ThisusestheRailshelperlink_totocreatelinks(whichwecreateddirectlywiththeanchortagainSection3.2.2)the
firstargumenttolink_toisthelinktext,whilethesecondistheURL. WellfillintheURLswithnamed
routesinSection5.3.3,butfornowweusethestubURL#commonlyusedinwebdesign(i.e.,#isjustastub,or
placeholder,fortherealURL). Thethirdargumentisanoptionshash,inthiscaseaddingtheCSSidlogotothesample
applink. (Theotherthreelinkshavenooptionshash,whichisfinesinceitsoptional.) Railshelpersoftentakeoptions
hashesinthisway,givingustheflexibilitytoaddarbitraryHTMLoptionswithouteverleavingRails.
Thesecondelementinsidethedivsisalistofnavigationlinks,madeusingtheunorderedlisttagul,togetherwith
thelistitemtagli:
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", '#' %></li>
<li><%= link_to "Help", '#' %></li>
<li><%= link_to "Log in", '#' %></li>
</ul>
</nav>
The<nav>tag,thoughformallyunnecessaryhere,isusedtomoreclearlycommunicatethepurposeofthenavigation
links. Meanwhile,thenav,navbar-nav,andnavbar-rightclassesontheultaghavespecialmeaningtoBootstrapand
willbestyledautomaticallywhenweincludetheBootstrapCSSinSection5.1.2. Asyoucanverifybyinspectingthe
navigationinyourbrowser,onceRailshasprocessedthelayoutandevaluatedtheembeddedRubythelistlookslike
this:5
<nav>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
<li><a href="#">Help</a></li>
<li><a href="#">Log in</a></li>
</ul>
</nav>
Thisisthetextthatwillbereturnedtothebrowser.
Thefinalpartofthelayoutisadivforthemaincontent:
<div class="container">
<%= yield %>
</div>
Asbefore,thecontainerclasshasspecialmeaningtoBootstrap. AswelearnedinSection3.4.3,theyieldmethod
insertsthecontentsofeachpageintothesitelayout.
Apartfromthesitefooter,whichwelladdinSection5.1.3,ourlayoutisnowcomplete,andwecanlookattheresultsby
visitingtheHomepage. Totakeadvantageoftheupcomingstyleelements,welladdsomeextraelementsto
thehome.html.erbview(Listing5.2).
Listing5.2: TheHomepagewithalinktothesignup
page.
app/views/static_pages/home.html.erb
<div class="center jumbotron">
<h1>Welcome to the Sample App</h1>
<h2>
InpreparationforaddinguserstooursiteinChapter7,thefirstlink_tocreatesastublinkoftheform
<a href="#" class="btn btn-lg btn-primary">Sign up now!</a>
Inthedivtag,thejumbotronCSSclasshasaspecialmeaningtoBootstrap,asdothebtn,btn-lg,andbtnprimaryclassesinthesignupbutton.
Thesecondlink_toshowsofftheimage_taghelper,whichtakesasargumentsthepathtoanimageandanoptional
optionshash,inthiscasesettingthealtattributeoftheimagetagusingsymbols. Forthistowork,thereneedstobean
imagecalledrails.png,whichyoushoulddownloadfromtheRailsTutorialwebsite
athttp://railstutorial.org/rails.pngandplaceintheapp/assets/images/directory.6 IfyoureusingthecloudIDEor
anotherUnixlikesystem,youcanaccomplishthiswiththecurlutility,asshowninListing5.3. (SeeLearnEnough
CommandLinetoBeDangerousformoreinformationaboutcurl.)
Listing5.3: Downloadinganimage.
$ curl -o app/assets/images/rails.png -OL railstutorial.org/rails.png
Becauseweusedtheimage_taghelperinListing5.2,Railswillautomaticallyfindanyimagesin
theapp/assets/images/directoryusingtheassetpipeline(Section5.2).
Nowwerefinallyreadytoseethefruitsofourlabors. YoumayhavetorestarttheRailsservertoseethechanges
(Box1.1),andtheresultsshouldappearasshowninFigure5.2.
Figure5.2: TheHomepagewithnocustomCSS.
Tomaketheeffectsofimage_tagclearer,letslookattheHTMLitproducesbyinspectingtheimageinourbrowser:7
<img alt="Rails logo" src="/assets/rails-9308b8f92fea4c19a3a0d8385b494526.png" />
Herethestring9308b8f92fea4c19a3a0d8385b494526(whichwilldifferonyoursystem)isaddedbyRailstoensure
thatthefilenameisunique,whichcausesbrowserstoloadimagesproperlywhentheyhavebeenupdated(insteadof
retrievingthemfromthebrowsercache). Notethatthesrcattributedoesntincludeimages,insteadusing
anassetsdirectorycommontoallassets(images,JavaScript,CSS,etc.). Ontheserver,Railsassociatesimagesin
theassetsdirectorywiththeproperapp/assets/imagesdirectory,butasfarasthebrowserisconcernedalltheassets
lookliketheyareinthesamedirectory,whichallowsthemtobeservedfaster. Meanwhile,thealtattributeiswhatwill
bedisplayedifthepageisaccessedbyaprogramthatcantdisplayimages(suchasscreenreadersforthevisually
impaired).
AsfortheresultshowninFigure5.2,itmightlookalittleunderwhelming. Happily,though,wevedoneagoodjobof
givingourHTMLelementssensibleclasses,whichputsusinagreatpositiontoaddstyletothesitewithCSS.
Exercises
1.Itswellknownthatnowebpageiscompletewithoutacatimage. UsingthecommandinListing5.4,arrangeto
downloadthekittenpicshowninFigure5.3.8
2.Usingthemvcommand,movekitten.jpgtothecorrectassetdirectoryforimages(Section5.2.1).
3.Usingimage_tag,addkitten.jpgtotheHomepage,asshowninFigure5.4.
Figure5.3: Anobligatorykittenpic.
Listing5.4: Downloadingacatpicturefromthe
Internet.
$ curl -OL cdn.learnenough.com/kitten.jpg
Figure5.4: TheresultofaddingakittenimagetotheHomepage.