Sie sind auf Seite 1von 4

4.3.

CSSrevisited

ItstimenowtorevisitthelinefromListing4.1usedinthelayouttoincludethecascadingstylesheets:
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload' %>

Wearenownearlyinapositiontounderstandthis. AsmentionedbrieflyinSection4.1,Railsdefinesaspecialfunctiontoincludestylesheets,and
stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload'

isacalltothisfunction. Butthereareseveralmysteries. First,wherearetheparentheses? InRuby,theyareoptional,sothesetwoareequivalent:


# Parentheses on function calls are optional.
stylesheet_link_tag('application', media: 'all',
'data-turbolinks-track': 'reload')
stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload'

Second,themediaargumentsurelookslikeahash,butwherearethecurlybraces? Whenhashesarethelastargumentinafunctioncall,thecurly
bracesareoptional,sothesetwoareequivalent:
# Curly braces on final hash arguments are optional.
stylesheet_link_tag 'application', { media: 'all',
'data-turbolinks-track': 'reload' }
stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload'

Finally,whydoesRubycorrectlyinterpretthelines
stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload'

evenwithalinebreakbetweenthefinalelements? TheansweristhatRubydoesntdistinguishbetweennewlinesandotherwhitespaceinthis
context.13 ThereasonIchosetobreakthecodeintopiecesisthatIprefertokeeplinesofsourcecodeunder80charactersforlegibility.14

context.13 ThereasonIchosetobreakthecodeintopiecesisthatIprefertokeeplinesofsourcecodeunder80charactersforlegibility.14
So,weseenowthattheline
stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload'

callsthestylesheet_link_tagfunctionwithtwoarguments:astring,indicatingthepathtothestylesheet,andahashwithtwoelements,
indicatingthemediatypeandtellingRailstousetheturbolinksfeatureaddedinRails4.0. Becauseofthe< % = % > brackets,theresultsareinserted
intothetemplatebyERb,andifyouviewthesourceofthepageinyourbrowseryoushouldseetheHTMLneededtoincludeastylesheet
(Listing4.14). (Youmayseesomeextrathings,like?body=1,aftertheCSSfilenames. TheseareinsertedbyRailstoensurethatbrowsersreload
theCSSwhenitchangesontheserver.)
Listing4.14: TheHTMLsourceproducedbytheCSSincludes.
<link data-turbolinks-track="true" href="/assets/application.css" media="all"
rel="stylesheet" />

4.4 Rubyclasses
WevesaidbeforethateverythinginRubyisanobject,andinthissectionwellfinallygettodefinesomeofour
own. Ruby,likemanyobjectorientedlanguages,usesclassestoorganizemethodstheseclassesaretheninstantiatedto
createobjects. Ifyourenewtoobjectorientedprogramming,thismaysoundlikegibberish,soletslookatsome
concreteexamples.

4.4.1 Constructors
Weveseenlotsofexamplesofusingclassestoinstantiateobjects,butwehaveyettodosoexplicitly. Forexample,we
instantiatedastringusingthedoublequotecharacters,whichisaliteralconstructorforstrings:
>> s = "foobar"

# A literal constructor for strings using double quotes

=> "foobar"
>> s.class
=> String

Weseeherethatstringsrespondtothemethodclass,andsimplyreturntheclasstheybelongto.
Insteadofusingaliteralconstructor,wecanusetheequivalentnamedconstructor,whichinvolvescalling
thenewmethodontheclassname:15
>> s = String.new("foobar")
=> "foobar"
>> s.class
=> String
>> s == "foobar"
=> true

# A named constructor for a string

Thisisequivalenttotheliteralconstructor,butitsmoreexplicitaboutwhatweredoing.
Arraysworkthesamewayasstrings:
>> a = Array.new([1, 3, 2])
=> [1, 3, 2]

Hashes,incontrast,aredifferent. WhilethearrayconstructorArray.newtakesaninitialvalueforthe
array,Hash.newtakesadefaultvalueforthehash,whichisthevalueofthehashforanonexistentkey:
>> h = Hash.new
=> {}
>> h[:foo]
=> nil
>> h = Hash.new(0)
=> {}
>> h[:foo]
=> 0

# Try to access the value for the nonexistent key :foo.


# Arrange for nonexistent keys to return 0 instead of nil.

Whenamethodgetscalledontheclassitself,asinthecaseofnew,itscalledaclassmethod. Theresultofcallingnewon
aclassisanobjectofthatclass,alsocalledaninstanceoftheclass. Amethodcalledonaninstance,suchaslength,is
calledaninstancemethod.
Exercises

1.Whatistheliteralconstructorfortherangeofintegersfrom1to10?
2.WhatistheconstructorusingtheRangeclassandthenewmethod? Hint:newtakestwoargumentsinthiscontext.
3.Confirmusingthe==operatorthattheliteralandnamedconstructorsfromtheprevioustwoexercisesareidentical.

Das könnte Ihnen auch gefallen