W T Au Di r Co H O W E B T R A W u thor: H r ecto r ‐dire c O W B ‐ A A VE W I T I N TE C H écto r r :Davi c tor:J u TO PP L LI N T H T N N O C H N r Yon e d de A u anCa r [1] D E L IC A N GS T H E O V A N O L e Laco r A ndré s rlosR E VE L A TI O OL U E M O A TI V L OG r tColl s Mart í u izG a L O P O N F U TI O O S T V E IES a do í nez a rcía P A F O R O N S T R S
[2] Resumen Se presentará el marco donde Waymate nació como idea conceptual, una aplicación que ofrece soluciones para viajar de una ciudad a otra mediante diferentes medios de transporte de una forma fácil en inteligente. Esta plataforma soporta aplicaciones cliente para web y dispositivos móviles. Sin embargo, este documento describe el procedimiento para crear la parte del cliente para la aplicación web, además de la parte del servidor, la cual es empleada para los diferentes clientes. Las diferentes técnicas del Ciclo de Vida de Desarrollo de Software serán descritas y la selección de estos diferentes métodos para éste propósito que concierne al desarrollo de la aplicación justificados. Existen diversas plataformas y tecnologías para implementar una aplicación de tal complejidad para la parte del cliente y del servidor, pero ¿cuáles de ellas son las adecuadas e innovadoras? Este documento abordará la descripción de diferentes alternativas para la implementación de diferentes características y funcionalidades requeridas para este tipo de aplicaciones, especificando las ventajas y desventajas que presentan, la razones porque han sido elegidas y los beneficios que aportan a la funcionalidad de la aplicación. Todas estas características descritas en los siguientes puntos, están consideradas a la vanguardia por diferentes comunidades de desarrolladores: Framework para el desarrollo de la parte del servidor. Ruby on Rails proporciona diversas características que permiten la implementación de una completa aplicación, en cuanto a cliente y servidor, ya sean incluidas en el mismo framework o en librerías externas. Entre estas funcionalidades, cabría destacar el almacenamiento de datos, servicios RESTful, internacionalización, configuración de activos, despliegue de nuevas versiones, testeo y el patrón de diseño y estructura de código MVC. Tecnologías de la parte del cliente. Librería que incluyen patrones innovadores para organizar el código y los archivos, como también una interfaz de usuario altamente interactiva. Despliegue de versiones. Exponiendo las últimas estrategias y procedimientos para llevar a cabo este proceso de una forma inteligente y fiable. Cómo testear antes de desplegar una nueva versión, porque usar multi‐staging, monitorizar pruebas una vez la nueva versión es accesible a través de una URL a todos los usuarios y como configurar estos frameworks. Mejora del rendimiento de la aplicación en la parte del cliente gracias a diferentes tecnologías empleadas. Diferentes procedimientos para testear todo el código posible, siguiendo metodologías de Desarrollo Guiado por Pruebas o por Comportamiento, para el código del cliente y servidor, además del flujo de datos. Con respecto a todas estas tecnologías, se proveerá de una descripción de consejos para su integración e implementación, de forma que un desarrollador de software pueda llevarlo a la práctica. Finalmente el flujo de datos y las diferentes etapas a lo largo de la aplicación serán descritos. Para las diferentes etapas ha sido necesario incluir servicios externos para facilitar la experiencia del usuario, tales como APIs proporcionadas por Google. Sus ventajas e inconvenientes también serán contrastados.
[3] Abstract It will be presented the frame where Waymate was born as a conceptual idea, an application which offers solutions to travel from a city to another by different means of transportation in an easy and smart way. This platform supports web and mobile client applications. However, this document describes the procedure for building up the clientside for the web app and the server-side, which is employed for all the different clients The different techniques of Software Development Life Cycles will be described and the selection of the different methods for the purpose which concerns the application development justified. There exist several platforms and technologies for building up such a complex application for the client and server-side, but which of them are the most appropriate and innovative? This document will tackle the description of different alternatives for implementing different features and functionalities required for this kind of applications, specifying the upsides and downsides which present, the reasons because they’ve been selected and the benefits which bring to the application functionality. All these features described in the following points are considered in the vanguard from several developer communities: Server-side framework. Ruby on Rails provides several features which allow implementing a complete server and client-side, either included in the framework or as external libraries. Among these features, it should be mentioned datastorage, RESTful services, internationalization, assets configuration, deployment, testing and the Model/View/Controller pattern. Client-side technologies. Libraries which include innovative patterns to organize the code and the files within the project, as well as a highly interactive user interface. Deployment. Exposing the latest strategies and procedures to carry out this process in a smart and reliable way. How to test before deploying, why using multi-staging, test-monitoring once the new version is on the live system after being deployed and how to configure all these frameworks. Performance improvements of the application on the client-side by means of different technologies employed. Different procedures to test all the testable code, following the Test-Driven and Behavior-Driven Development methodologies, for the client and server-side code, as well as the workflow. Regarding these technologies, technical insights and advices for their integration and implementation will be described in a way that could help to a developer who wants to use them. Finally the workflow and the different stages along the application will be described. For the different stages it’s been necessary to include external services to facilitate the user experience along the process, such as Google APIs. The pros and cons of all these features will be contrasted.
[4] Index Resumen........................................................................................................................................1 Abstract.........................................................................................................................................3 Tableofimages.............................................................................................................................6 Tableofcodesnippets..................................................................................................................7 1.INTRODUCTION.........................................................................................................................8 Waymateasaconceptualidea.................................................................................................9 Documentstructure................................................................................................................10 2.SOFTWAREDEVELOPMENTLIFECYCLE...................................................................................11 3.SERVER‐SIDE............................................................................................................................14 Alternativesfordevelopingawebapplication.......................................................................14 RubyonRails...........................................................................................................................16 3.1.Railscomponents.........................................................................................................16 3.2.Railsenvironments.......................................................................................................18 3.3.MVCinRails..................................................................................................................19 3.4.Railsinternationalization..............................................................................................32 3.5.Testing..........................................................................................................................34 3.6.AssetPipeline...............................................................................................................39 4.DEPLOYMENTPROCESS...........................................................................................................42 4.1Web‐basedhostingservice...............................................................................................42 4.2.Git.Distributedrevisioncontrol.......................................................................................43 4.2.1.Git’sdatastructures..................................................................................................44 4.2.2.Gitfromtheconsole..................................................................................................45 4.2.3.Conflicts.....................................................................................................................48 4.3.Capistranodeployment....................................................................................................49 4.4.Multistage........................................................................................................................52 4.5.Testingbeforedeploying..................................................................................................53 4.5.Websitemonitoringsystem.............................................................................................54 TinyMon..............................................................................................................................54 5.APIsdataabstractionintoacommonobject..........................................................................56 5.1.DeutscheBahnAPI...........................................................................................................56
[5] 5.2.YpsilonAPI........................................................................................................................57 6.CLIENT‐SIDE.............................................................................................................................59 6.1HTML.................................................................................................................................59 6.2.HTMLappearanceelements............................................................................................60 6.2.1.CSS.............................................................................................................................60 6.1.2.SASS...........................................................................................................................61 6.3.Dynamicweb‐site.............................................................................................................64 6.3.1.JavaScript...................................................................................................................64 6.3.2.AJAX...........................................................................................................................64 6.3.3.jQuery........................................................................................................................65 6.3.4.Backbone...................................................................................................................66 6.3.5.Testingtheclient‐side...............................................................................................76 7.Waymate.Howitworks..........................................................................................................79 7.1.Objectmodelsontheserver‐side....................................................................................79 7.2Workflowalongtheentireprocess...................................................................................83 7.2.1.Landingpage.............................................................................................................84 7.2.2.Searchpage...............................................................................................................86 7.2.3.Resultspage..............................................................................................................92 7.2.4.Detailspage...............................................................................................................96 7.2.5.Bookingform.............................................................................................................99 7.2.6.Tickets.....................................................................................................................104 7.2.7.Hotelsbooking........................................................................................................105 Conclusion.................................................................................................................................106 References.................................................................................................................................108
[6] Tableofimages Image1:Newfeaturedevelopmentcycle..................................................................................13 Image2:Bug‐fixingcycle.............................................................................................................13 Image3:Requestforgeryattack.................................................................................................29 Image4:Gitstates,workflowandareas.....................................................................................44 Image5:Masteranddevelopbranches......................................................................................46 Image6:HierarchyofobjectmodelswhichcomposeanOrder.................................................80 Image7:HierarchyofobjectmodelswhichcomposeaTour.....................................................81 Image8:Landingpage................................................................................................................84 Image9:Emailsubscription........................................................................................................84 Image10:Loginwindowinlandingpage...................................................................................85 Image11:Searchpage.GooglePlacesauto‐completion............................................................86 Image12:Searchpage.Calendar................................................................................................89 Image13:Searchpage.Travelers...............................................................................................90 Image14:Resultspage.MapandNavigationtabs.....................................................................92 Image15:Resultspage.Travelerconnectionpreferences.........................................................93 Image16:Meanoftransportationfilters....................................................................................93 Image17:Durationsliderfilter...................................................................................................93 Image18:Pricerangesliderfilter...............................................................................................93 Image19:Timesliderfilter.........................................................................................................94 Image20:Sortingfunctions........................................................................................................94 Image21:Travelersprofilecustomization..................................................................................94 Image22:SpecialPricecheckbox...............................................................................................95 Image23:Resultspage.Connectionsframe...............................................................................95 Image24:Detailspage................................................................................................................96 Image25:Detailspage.Generalrepresentationofaconnection..............................................97 Image26:Detailspage.Connectiondetailsexpanded...............................................................97 Image27:Detailspage.Priceswitching......................................................................................97 Image28:Detailspage.Conditionsforatypeofprice...............................................................97 Image29:Detailspage.Travelersprofileset..............................................................................98 Image30:Bookingform.Travelerprofilesetanddetailsviewforselectedconnections.........99 Image31:Bookingform.Seatreservationconditions..............................................................100 Image32:Bookingform.Seatselection....................................................................................100 Image33:Bookingform.Customerpersonaldataandaddress...............................................101 Image34:Bookingform.Creditcardinformation....................................................................101 Image35:Bookingform.Onlineidentification.........................................................................101 Image36:Bookingform.Travelers’personalinformation.......................................................102 Image37:Bookingform.Termsandconditions.......................................................................102 Image38:Pop‐uperrorswhenvalidationfails.........................................................................103 Image39:Tickets.Travelerspreferencessetanddetailsviewforpurchaseconnections.......104 Image40:Tickets.Ticketspurchaselinksandinformation......................................................104 Image41:Hotelsbooking..........................................................................................................105
[7] Tableofcodesnippets Codesnippet1:Databaseconfigurationfordevelopmentenvironment...................................18 Codesnippet2:Migrationfiletemplate.....................................................................................22 Codesnippet3:Layoutfileskeleton...........................................................................................24 Codesnippet4:Bookobjectboundtoaform............................................................................26 Codesnippet5:Resourcesdefinedunderthe‘admin’scope....................................................30 Codesnippet6:Routenamesspecifiedexplicitlyfor‘login’and‘logout’..................................30 Codesnippet7:ChunkfromtheEnglishtranslationfile............................................................32 Codesnippet8:Implementationtosetthelocalefromthebrowserheader............................32 Codesnippet9:Localescopedefinitionforthelanguagessupported.......................................33 Codesnippet10:UnittestwithtwoassertionsforaCustomerTestmodel...............................35 Codesnippet11:RequiredlinesforBDDlibrariesinclusionintheBDDtestingenvironment...37 Codesnippet12:Scenarioexample............................................................................................38 Codesnippet13:Stepdefinitionsforascenario........................................................................38 Codesnippet14:JavaScriptfilesinclusionintheprojectfromtheapplication.jsfile................40 Codesnippet15:JavaScriptfilesorganization............................................................................40 Codesnippet16:Compressionlibrariesinclusionintheproductionenvironment...................41 Codesnippet17:Repositorycreationingit................................................................................45 Codesnippet18:TemplatetoproxytheMongrelwithawebsite.............................................51 Codesnippet19:Multistagingconfigurationfortwodifferentstages.......................................52 Codesnippet20:IntegrateTyniMonintheproductionstage....................................................55 Codesnippet21:ExceptionNotifierconfiguration......................................................................55 Codesnippet22:SASS.Variabledefinitionexample..................................................................62 Codesnippet23:SASS.Nestingclasesexample.........................................................................62 Codesnippet24:SASS.Mixinfunctionexample.........................................................................63 Codesnippet25:JavaScriptlibraryinclusionfromaHTMLtemplate........................................65 Codesnippet26:Backbone.JavaScriptfilesorganization..........................................................66 Codesnippet27:Backbone.Modeldefinition............................................................................69 Codesnippet28:Backbone.Routerdefinitionexample............................................................74 Codesnippet29:Backbone.Viewdefinitiontemplate...............................................................75 Codesnippet30:Testsuitedefinitionwith4Specs...................................................................77 Codesnippet31:Migrationfileexamplewhichintroducesorremovesanairline....................80
[8] 1.INTRODUCTION Nowadays,peopleareusedtotravelquiteoftengiventhefacilitiesthatdifferent meansoftransportationoffer.OnlyinsidetheGermanboundaries,alongoneyear,10billion oftravelsarecarriedout.However,thereisnoacompletesupportfromtheexisting technologiesalongthejourneysinthemarket. Whentravelerslandinanunknowncity,theycouldfeellostandasktosomepeople howtogettotheirdestination.Theywon’tprobablyfindthefastandcheapwaytotravel withinthecityfromonepointtoanother.Howthiscanstillhappeninsuchacomputerized world? Currently,withthefastevolutionoftechnologies,smartphonesarebecomingmore powerfulasdaysgoby.Thesemobilephonesprovidemuchmorethanjustmakingcallsor sendingmessages.Itcanbeusedforcommunicationandcomputingpurposes,becausethey runacompleteoperatingsystem,canconnecttointernetandnavigate,haveGPS,andmore otherfeatures.Theycouldbeconsideredassmallcomputersgiventhecapabilitieswhich presentandpossibilitieswhichoffer. Thenumberofuserswhoownasmartphoneisgrowingcontinuouslydayafterday. Peoplegoeseverywherewithasmallcomputerintheirpocket.Dueitspower,it’semployfor makinglifeeasierhavingalargeamountofapplicationwhichhelpsdailytomillionsofusers. Nevertheless,travelersdon’thaveyetanapplicationavailableinthemarketwhich providesacompletesupportwhentravelingforlongandshortdistance,allinone. Inthemarket,thereexistapplicationswhichoffertravelsolutionsforlongdistance fromwebandmobileappsinasmartway,suchas“Hipmunk”. Forshortdistance,usingpublictransportation,thereexistseveralapplications,but usuallyonlysupportasinglecity.Googleisinprogressofdeveloping“GoogleTransit”offering alltheconnectionsfordeterminedcitiesallovertheworld,buttherearealotofcitiesmissing inGermany,andnotallthepublicmeansoftransportationareincluded. Italsoexistwebapplicationswhichincludetravelsolutionsforshortandlong distance,butthewaytheypresenttheinformationisnotsoclear,suchas“Rome2rio”. Otherapplicationsofferinformationaboutdifferentkindsofplacesnearbysuchas “Google+Local”. Thenimagineanapplicationavailableforwebandmobiledeviceswhichincludesall thesefeaturesinone,offeringaclearandfancyinterfaceaswellasasimpleinteraction. HereiswhereWaymateasaconceptualideabegins.
[9] Waymateasaconceptualidea Themainideaistobuildupanapplicationwhichpresentsdoor‐to‐doortravel solutions,includingshortandlongdistance,inaclearandsmartwaywheretheusercould perceiveadvantagesforitspreferredconditions. Besides,theapplicationwillpresentdifferentsolutionsforgoingfromanorigintoa destinationpoint.Alltheexistingmeansoftransportationwhichhelptocoverthejourneywill beincluded,suchastrains,flights,publictransport,car‐sharing,car‐renting,andsoon.Within thissetofsolutionsuserswillbeabletosettheirpreferences.Hence,thesolutionswhichfit betteraccordinglytotheuserpreferenceswillbepresented. Ticketspurchasewillbebundledinonesinglebookingprocess,insteadofbuyingeach ticketseparately,makingtheprocesseasierandfaster. Awebandmobileclientapplicationwillsupportshortandlong‐distance.However,the mainfunctionalitywhichuserswillemployintheweb‐applicationwillbetoplaninadvance long‐distancejourneys.Ontheotherhand,mobileapplicationwillbemeanttoprovide supportduringthejourney,suchasfindingplacesnearby,representationofthecurrentstage alongthejourneysuchasremainingtimeandcurrentlocation,aswellasofferinstantaneous solutionsforshortdistance. Itwillbepossibletoplanthetripregardingtheconnectionsthetravelerwilltake beforestartingit.Thismeanswhentheuserarrivestoacitywherethereisnointernetaccess throughhissmartphone,thepathoverthemapwithalltheconnectionsandinformationwill besaved Thiswillbethedevelopingprocessfortheweb‐application,becomingmorecompleteafter eachstep: 1) ThefirstversionwillcovercompletelylongdistancewithinEuropebyflights,but outsidetheGermanboundaries,trainconnectionswillbeofferedonlyforimportant cities. 2) Thesecondversionwillcoverlongdistancebyflightsallovertheworld. 3) ThethirdwillincludesolutionsforshortdistanceinsideGermany. 4) Inthefollowingversions,onceGermanyisfullycovered,theapplicationwillexpand theboundariestotheadjacentcountriesfortrainandpublictransport. Inparallelwilltakeplacethedevelopmentoftheapplicationformobiledevices.This developmentwillfollowthesamesteps,thanthewebappandasthehardworkforgettingall thatfunctionalityisimplementedontheserverside.Then,itwillbetimefordevelopingthe featuresmentionedpreviouslyforgivingsupporttotravelersalongthejourneyaseverything isadvancinginthewebapp. Thebusinessmodelistogetapercentageofthetrainandflightticketsboughtthroughthe platform,aswellashotelsbooking.Lookingforward,probablythisplatformwouldoffer discountsforgoingtoarestaurant,forshoppinginadeterminedshopordoingwhatever activityinthedestinationcity.
[16] RubyonRails RubyonRailsisanopensourcefull‐stackwebapplicationdevelopmentframework writtenintheRubylanguage.ItgivestotheWebdeveloperthefullabilitytogather informationfromthewebserver,talkingorqueryingthedatabaseandtemplaterenderingout ofthebox. InRailsprevailsConventionoverConfiguration,whichmeansmakingassumptions aboutwhatandhowtodoit,ratherthanrequiringspecifyingeverylittlethingthroughendless configurationfiles. RailsincludesapackagemanagecalledRubyGemsfortheRubyprogramminglanguage whichprovidesastandardformatfordistributingRubyprogramsandlibraries,inaself‐ containedformatcalledagem.Thistoolwasdesignedtoeasilymanagetheinstallationof gems,andaserverfordistributingthem.Forinstallinganduninstallingagem,intheconsole it’styped: geminstall<gem_name>orgemuninstall<gem_name> 3.1.Railscomponents3 Action Pack ActionPackisasinglegemthatcontainsActionController,ActionViewandActionDispatch, whichisthe“VC”partof“MVC”. 1. ActionControlleristhecomponentthatmanagesthecontrollersinaRailsapplication. TheActionControllerframeworkprocessesincomingrequeststoaRailsapplication, extractsparameters,anddispatchesthemtotheintendedaction.Servicesprovidedby itincludesessionmanagement,templaterendering,andredirectmanagement. 2. ActionViewmanagestheviewsoftheRailsapplication.Itcancreate bothHTMLandXMLoutputbydefault.ActionViewmanagesrenderingtemplates, includingnestedandpartialtemplates,andincludesbuilt‐inAJAXsupport. 3. ActionDispatchhandlesroutingofwebrequestsanddispatchesthemasyouwant, eithertoyourapplicationoranyotherRackapplication. Action Mailer ActionMailerisaframeworkforbuildinge‐mailservicelayers.Theselayersareusedto consolidatecodeforsendingoutforgottenpasswords,welcomesforsigningup,inboxesfor billingoranyothernotification.Itprovidesawaytomakeemailsusingtemplates.Itcanalso beusedtoreceiveandprocessincomingemail. 3RubyonRailscomponents:http://guides.rubyonrails.org/getting_started.html
[17] Active Model ItprovidesadefinedinterfacebetweentheActionPackgemservicesandObject RelationshipMapping(ORM)gemssuchasActiveRecord.ActiveModelallowsRailstoutilize otherORMframeworksinplaceofActiveRecordiftheapplicationneedsit. Active Record ItisthebaseforthemodelsinaRailsapplication.Itprovidesdatabaseindependence, thefourbasicfunctionsofpersistencestorage,create,read,updateanddelete(CRUD), advancedfindingcapabilities,andtheabilitytorelatemodelstooneanother,amongother services. Active Resource Itprovidesaframeworkformanagingtheconnectionbetweenbusinessobjectsand RESTful(Representationalstatetransfer)webservices,anapproachforgettinginformation contentfromtheserver‐side.Itimplementsawaytomapweb‐basedresourcestolocal objectswithCRUDsemantics. Active Support AnextensivecollectionofutilityclassesandstandardRubylibraryextensionsthatare usedinRailsbythecorecodeandapplications. Railties RailtiesisthecoreRailscodethatbuildsnewRailsapplicationsandgluesthevarious frameworksandpluginstogetherinanyRailsapplication.
[18] 3.2.Railsenvironments Railshastheconceptofenvironmentstorepresentthestagesofan application’slifecycle.Itincludesasdefaultthesethreeenvironments: Test,usedforrunningRailsbuiltintestsuite. Development,isthedefaultenvironment,optimizedforrunninglocally.Full errormessagesaredisplayed,cachingisdisabled,andclassesare automaticallyreloaded,meaningthatit’snotnecessarystartandstoprunning thelocalserverforupdatingthechanges. Production,configuredforspeedandsecurity.Cachingisenabled,classesnot reloaded,anderrormessagesonlyhavesimpleerrorcodes,insteadoffullback tracesandsessioninformation. Eachenvironmenthasacorrespondingenvironmentfile config/environments/environment_name.rbwithitsparticularconfigurationcode.Every environmenthasitsowndatabaseaswell,definedinconfig/database.yml.Fordevelopment, thesectionfortheproductiondatabaseisconfiguredasfollows: development: adapter:mysql2 database:db_development username:root password: host:127.0.0.1 encoding:utf8 Codesnippet1:Databaseconfigurationfordevelopmentenvironment Intheconsole,thiscommandneedstobeintroducedforstartingtheserverinthe otherdifferentenvironmentthandevelopment: rails server --environment test or rails server –environment production
[19] 3.3.MVCinRails4 RailsusestheModel/View/Controller(MVC)architecturepatterntoorganizeapplication programming.ThebenefitswhichMVCincludesare: Isolationofbusinesslogicfromtheuserinterface.Itkeepsseparatedthe representationofinformation,logicanduserinteraction. EasytokeeptheDRY(Don’tRepeatYourself)philosophy.Theideabehindistoreuse thedifferentmodulesinseveralplaces,avoidingcoderepetition. Makingitclear,wherecodeiswellstructuredandorganizedproperlyintheir correspondingmodules. 3.3.1MVCcomponents 1. Modelsrepresenttheinformationordataoftheapplicationandtherulesto manipulatethatdata.InRailstheyareusedformanagingtherulesof interactionwithacorrespondingdatabasetable.Inmostcases,eachtablewill correspondtoonemodelintheapplication. 2. Viewsrepresenttheuserinterfaceoftheapplication.InRails,viewsareoften HTMLfileswithembeddedRubycodethatperformtasksrelatedsolelytothe presentationofthedata.Theyprovidedatatobethedisplaytotheweb browser. 3. Controllersarethelinkbetweenmodelsandviews.InRails,controllersare responsibleforprocessingtheincomingrequestsfromthewebbrowser, askingtomodelsfordataandpassingthatdataontotheviewsfor representation. 4MVCinRails:http://guides.rubyonrails.org/getting_started.html#the‐mvc‐architecture
[20] 3.3.2Models AmodelisanActiveRecordobjectwhichincludeshooksintothisobjectlife cycletothedatabasepersistency,controllingtheapplicationanditsdata. Creatingandsavinganewrecord,RailswillsendautomaticallyanSQLINSERT operationtothedatabase.UpdatinganexistingrecordwillsendanSQLUPDATE.Ifany validationsfail,theobjectwillbemarkedasinvalidanditwon’tperformanyoperation. 3.3.2.1 Validations Validations5arepreconditionsdefinedintheclassmodel,whichareassociatedto attributesandshouldbeaccomplishedbytheattributevaluebeforebeingstoredinthe database.Thesevalidationsaredefinedinthefilewhichcontainstheclassandinthesameline thanthecorrespondingattributewhichwillbeassociated.ActiveRecordusesthemtoensure thatonlyvalidobjectsaresavedintothedatabase. ActiveRecordofferspre‐definedvalidationhelpersthatcanbeuseddirectlyinthe classdefinitions.Thesearemostcommonhelpers: 1. format=>attribute’svaluesshouldmatchtoagivenregularexpression. 2. length=>thevalueshouldhavethesamelengththantheonespecified. 3. numericality=>shouldonlycontainnumericvalues. 4. presence=>theattributeisnotempty. 5. uniqueness=>theattribute’svaluemustbeunique. 3.3.2.2 Database RailsincludesasdefaultRelationalDatabaseManagementSystem(RDBMS)SQLite3. Thisapplicationismeanttohavemanyclientsaccessingtoacommondatabase, writingandreadingconcurrentlyoveranetwork.Hence,itwillbeneededaRDBMSwhichwill allowaparallelaccesstodifferentusers. SQLiteisanembeddedrelationaldatabaseintowhichrunsin‐processwiththe applicationandreadsandwritesasingledatabasefile.SQLitewillworkoveranetwork filesystem,butbecauseofthelatencyassociatedwithmostnetworkfilesystems,performance willnotbegreat.Furthermore,SQLiteshouldn’tbeusedwhenaccessingthedatabase simultaneouslyfromdifferentcomputersoveranetworkfilesystem,duetowhenuserswrite, lockontheentirefile. 5Modelvalidations:http://guides.rubyonrails.org/active_record_validations_callbacks.html
[21] Ontheotherhand,MySQLisarelationaldatabaseserverthatisaccessedviaa networkconnection.Itrunsaserverprovidingmulti‐useraccess,giventhatwebserverscan handlemultiplerequestsconcurrently,andeachofthesecouldbeconnectedtothedatabase. Summarizing,SQLiteistheproperRDBMStoworkwithstandaloneapplications.For client‐serverapplicationsandmorecomplexdeploys,itshouldbeusedMySQL. 3.3.2.3 Database migrations Databasemigrations6areaconvenientwaytoalterthedatabaseinastructuredand organizedway.ActiveRecordtrackswhichmigrationshavealreadybeenrun. Forrunningmigrationsalreadycodedbutnotexecuted,it’sjustneededtotyperake db:migrateandRailswilldotherest,workingoutmigrationswhichstillneedstoberun,updating thedatabaseandthefiledb/schema.rb,whichcontainsthestructureofthedatabase application. Whenthereismorethanonemigrationtobeexecuted,theywillrunsequentiallyas theywereimplementedintime.Ifsomethingfailsinthisprocess,migrationscompletely executedwillchangethedatabase,butnotthoseimplementedaftertheonewhichprovoke theerror,includingitself. ActiveRecord’sfunctionalityabstractthesyntaxinawaythatthestructuredefined andcommandsCRUDareindependentoftheRDBMSemployed.ItcanbeusedSQLitefor developmentenvironmentandMySQLforproduction. MigrationsaresubclassesofActiveRecord.Eachofthemimplementsthemethodup, toperformthepertinenttransformationsanddown,torevertthechanges.Thesearethe functionstomodifythedatabasewhichActiveRecordprovides: add_colum,add_index,change_colum,change_table,create_table,drop_table, remove_column,remove_index,rename_columandrename_table. ItispossibletodefinemigrationswritingtheSQLcodewithoutthehelpofthe functionsmentionedpreviously.Therefore,Railskeepsprovidingflexibilitywhendefininga newmigration. Wheneveramigrationisrun,canbeundonebytypingrakedb:rollback.Forthosecases whereadeveloperusesthemethodswhichActiveRecordsupply,Railshasintroducedthe changemethodwhichknowshowtorevertthechangesautomatically,withouttheneedof writingtheupanddownmethods.Ifothermethodsarerequireditisnecessarytoprogram theproperdownfunctioninordertogetthepreviousstateinthedatabaseincasethose changeshaven’tbeenexecutedasitwasexpected. 6Databasemigrations:http://guides.rubyonrails.org/migrations.html
[22] Railsincludesamigrationgenerator.Itmustbeexecutedintheconsolethefollowing tocreateanewone:railsgeneratemigration<name_migration> Afilewhichwouldlikethis class<name_migration><ActiveRecord:Migration defchange end end Codesnippet2:Migrationfiletemplate willbestoredinthedb/migratedirectoryintheform YYYYMMDDHHMMSS_<migration_name>.rb,includingthetimestampandmigrationname. Theyareorderedinthisdirectoryastheyoccurredintime,soadeveloperhasabetter understandingabouthowthedatabasehasbeenmodifiedregardingthetimeline. Specificindividualorsetsofmigrationscanberunorreverted.Specifyingatarget version,ActiveRecordwillruntherequiredmigrations(up,downorchange)untilithas reachedthestipulated. Givenallthissetoffunctionalities,Railsallowsretrievingthedesiredpreviousstate andkeepingtrackofeverychangewhichmodifiedthedatabase. Itishighlyrecommendedjustcreatingthestructureofthedatabaseandnotinserting datafrommigrations.Ifnewdevelopersjointheteam,orthesystemneedstobesetitup againforsomereason,executingthecommandrakedb:setupshouldexecuteallthemigrations sequentiallyuntilgetthecurrentstate.However,whenintroducingdatabymigrations,thisis notpossiblealways,giventhatatsomepoint,asinglemigrationcouldinterrupttheprocessif itcannotbeexecuted.Inthiscase,thedatabasecanbesetproperlywithadumpofthe currentversionfromtheproductionenvironmentorfromotherprogrammerwhoownsa databasewiththecurrentstate. 3.3.2.4 Associations InRailsanassociation7isaconnectionbetweentwoActiveRecordmodels. Associationsareusedinordertoaddfeaturestothemodelsdeclaratively.Theseare supportedtypes: 1. belongs_to=>one‐to‐oneconnectionwhereeachinstanceofthedeclaringmodel “belongsto”oneinstanceoftheothermodel 2. has_one=>one‐to‐oneconnectionwhereeachinstanceofamodelcontainsor possessesoneinstanceofanothermodel. Aninstancecanalsobematchedbyproceedingthoughathirdmodelbyhas_many :through. 7Associations:http://guides.rubyonrails.org/association_basics.html
[23] 3. has_many=>Createsaone‐to‐manyconnectionandeachinstanceofthemodelhas zeroormoreinstancesofanothermodel. Intancescanalsobematchedbyprocedingthoughathirdmodelbyhas_many:through. 4. has_and_belongs_to_many=>Createsadirectmany‐to‐manyconnectionwithanother model,withnointerveningmodel.
[24] 3.3.3Views ViewsinRailsareHTMLcodeaccompaniedofEmbeddedRubycode,whichallowsto accessinformationwhichislocatedontheserver‐sidefromthetemplates.Railscanmake templatesmoredynamicdueRubycodecouldbeusedwithinthem.Alltheviewsfeaturesin Railsaredescribedinthesub‐sectionsbelow. 3.3.3.1 Layouts and Rendering in Rails Thecodewhichrenderstheviewsisplacedinthecorrespondingcontroller.Bydefault, controllersautomaticallyrenderthelayoutfile,namedas<controller_name>.html.erb,which islocatedunderthedirectoryapp/views/layoutsandifitdoesn’texistalayoutwithaname whichiscorrespondedtothatcontrollerwillrendertheapplication.html.erblayoutfile.This happenswherethereisnocalltothefunctionrenderspecifyingexplicitlywhatit’swantedto display.Nevertheless,itcouldbedefinedrenderedadifferentlayoutfile,byrender:layout=> “<layout_name>”,whichhastobeunderthedirectoryspecifiedpreviously,orrenderatemplate whichcorrespondstothenameofthecontroller,withoutrenderinganylayoutwithrender :layout=>false Withinthecontextofalayout,yieldidentifiesasectionwherethecontentfromthe viewshouldbeinserted.Thesimplestwaytoproceedis: <html> <head> </head> <body> <%=yield%> </body> </html> Codesnippet3:Layoutfileskeleton Fileswithhtml.erbextension,HTMLEmbeddedRuby,areHTMLfileswhichcancontain RubycodeanditshelpersforHTMLelements.Thesefilesareevaluatedontheserverside,so variablesdefinedinthecontrolleritselforinadifferentfile,canbeusedwithinthesefiles.To triggerRubycodeinthistemplatesmustbeembeddedinsidethetags<%…%>,fornot displayinganycontent,beingusefulforoperatingwithvariables,creatingloops,if‐else conditions,andsoon.Forvisualizingoutputinsidethistag<%=…%> 3.3.3.2 Render method Therendermethod8doesaheavyliftingofrenderingtheapplication’scontentfor beingusedbyabrowser.IttellsRailswhichvieworassettousewhenconstructingthe response.Themostcommonwaystocustomizethisfunction: Torendertheviewthatcorrespondstoadifferentactionwithinthesame template: render:editorrender:neworrender:edit,etc. 8Rendermethod:http://guides.rubyonrails.org/layouts_and_rendering.html#using‐render
[25] Torenderatemplatefromadifferentcontroller: render‘<controller_name>/<action_view>’ ForrenderingaresponsewhenusingaRESTfulservice,inJSONorXMLformat: render:json=>@class_to_be_renderedorrender:xml=>@class_to_be_rendered Forrenderingadeterminetemplateorlayout,whichisnotanaction’sview andit’slocatedunderthedirectoryapp/views/<controller_name>or app/views/layout: render:layout=>‘<template_name>’ Ifitwouldbeinadifferentfile render:layout=>‘<controller_name>/<template_name>’ AnotherwaytohandlereturningresponsestoanHTTPrequestiswithredirect_to.This methodtellsthebrowsertosendanewrequestforadifferentURL.Comparingthemethod renderwithredirect_to,thedifferenceisbasicallythatthecodestopsrunningandwaitsfora newrequestforthebrowser. 3.3.3.3 Partials Partialtemplatesareanotherfeatureforbreakingtherenderingprocessinto moremanageablechunks.Furthermore,itmakeseasierthereusabilityofsnippetswhichare repeatedindifferentfiles.Forinstance,forcontentthatissharedamongallpagesinthe application,suchasafooter,partialscanbeuseddirectlyfromlayouts. Partialscanevenreceiveasargumentslocalvariables,makingthemmorepowerful andflexible. <%=render:partial=>“book”,:locals=>{author:@book.author,title:@book.title}%> Otherimportantfeaturewhichpartialsincludeistorendercollections.Whena collectionispassed,thepartialwillbeinsertedonceforeachmemberwithinthecollection. <%=render:partial=>“book”,:collection=>“library”%> 3.3.3.4 Action View Helpers9 Railsprovidesabunchofhelpersforgeneratingformelementssuchascheckboxes, textfields,radiobuttonsanddropdownlists.Theirnamesendwith_tag,suchas text_field_tag,whichgeneratesasingle<input>element.Railsusesconventionstomake possibletosubmitparameterssuchasarraysorhashesthatwillbeaccessibleinparams. 9Actionviewhelpers:http://guides.rubyonrails.org/form_helpers.html
[32] 3.4.Railsinternationalization Inordertoprovideamulti‐languagesupportfortheapplication,RailsincludesaRuby gem,so‐calledI18n15,whichprovidesaneasy‐to‐useandextensibleframeworkfortranslating theapplication. Foreachlanguagesupported,afilewiththeformatYAMLandextension.ymlmustbe includedunderthedirectoryconfig/locales.Thesefilesarenamedwiththe:localeofthe languagethatwillsupportandcontainthetranslationstrings.Thefilewhichcontainsthe Englishtranslationswouldlooklikethis: en: login: username:“Username” pass:“Password” Codesnippet7:ChunkfromtheEnglishtranslationfile Indentationisquiteimportant,becauseitallowsnestingtranslation,implementinga betterstructuretothefile.Butifthereissomelinewithwrongindentation,theapplication complainstriggeringanexception. Thewayitworksisabstractingallstringandotherlocalespecificfeatures,suchasdate orcurrencyformats,intheapplication.Railsaddsthefilesmentionedabove,tothe translationsloadpath(I18n.load_path)automaticallyandmakesthemavailableinthe application.Thentranslationsarelookedupbykeys,gettingthepropervaluesand instantiatingthevariablesdefinedintheviewtemplate. To<%=t‘login.pass’%>,ifthelocaleissetto:en,itwillprintPassword. Ifthedefaultlocaleisnotspecifiedexplicitly,itwillsetas:en(English).However, Waymatehasthedefaultas:de(German).Tosetthisvalue,thislineisaddedinapplication.rb: config.i18n.default_locale=:de It’swasconsideredconvenienttogetthelocalefromtheclientsuppliedinformation. ThisinformationmaycomeeitherfromtheIPorthebrowser.Togetthelocalefromtheuser’s preferredlanguageinthebrowserisagoodsolutionandsimpler,becauseotherwisetheIP havetobelookedupinadatabasetoidentifyfromwhichcountrycomestherequesttothe server.Atrivialimplementationisprovidedinthissnippet: defset_locale logger.debug"*Accept‐Language:#{request.env['HTTP_ACCEPT_LANGUAGE']}" I18n.locale=extract_locale_from_accept_language_header logger.debug"*Localesetto'#{I18n.locale}'" end private defextract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a‐z]{2}/).first end Codesnippet8:Implementationtosetthelocalefromthebrowserheader 15RailsinternationalizationwithI18n:http://guides.rubyonrails.org/i18n.html
[33] Toaddthelocaletotheroutesthescopelocalemustwrapallthecontentdefinedwithinit. scope'/:locale',:locale=>Regexp.new(I18n.available_locales.join('|'))do #declaredroutes end Codesnippet9:Localescopedefinitionforthelanguagessupported Thislineavoidsthematchingwithlocalesnotdefinedorsupported,settingas availableintheapplicationenandde.
[34] 3.5.Testing Runningtestsitensuresthatthecodeadherestothedesiredfunctionalityandmakes easiertodetectbugs.Railsprovidesaskeletontestcodeinthebackgroundwhenmodelsand controllersarecreated. 3.5.1Test‐DrivenDevelopment Ontheserver‐side,WaymatedevelopersfollowtheTest‐DrivenDevelopment(TDD)16 assoftwareprocess.Inthisprocess,firstthedeveloperwritesan(initiallyfailing)automated testcasethatdefinesadesiredimprovementornewfunction,thenproducestheminimum amountofcodetopassthattestandfinallyrefactorsthenewcodetoacceptablestandards. Though,sometimesdevelopersfollowthelogictheotherwayaround,implementing functionalityandthencreatingtests.Intheend,themainideaisnotaddingnewfunctionality withouthavingbeentested. Tomakethisprocesspossible,Railsprovidesthefollowingcomponents: 3.5.1.1 Fixtures Fixtures17allowpopulatingthetestingdatabasewithpredefineddatabeforethetests runandaredatabaseindependent.FixtureareYAML‐formatted,beinghuman‐friendlyfor describerdata. Bydefault,Railsloadallfixturesfromthetest/fixturesforunitandfunctionaltests.The threestepswhichinvolvethisprocessare: Removeanyexistingdatafromthetablecorrespondingtothefixture. Loadthefixtureintothetable. Dumpthefixturedataintoavariableincaseofaccessingitdirectly. TheirformatisasaHashobject.Neverthelessfixturescanalsotransformthemselves intotheformoftheoriginalclass,havingaccesstothemethodsforthatclasstoo. 3.5.1.2 Unit testing Unittests18areusefulfortestingsmallchunksofcode.Adevelopermustprogram testablecode,becauseotherwisethesekindoftestwillbedifficulttowriteornotpossibleat all. InRailsunittesting’scommonuseisforindividualfunctions,whereideallyeachtest caseisindependentfromtheother.Asagoodpractice,atitshouldbecreatedatleastonetest forvalidationsandforeverymethodwithinthemodel 16Test‐DrivenDevelopment:http://en.wikipedia.org/wiki/Test‐driven_development 17Fixtures:http://guides.rubyonrails.org/testing.html#the‐low‐down‐on‐fixtures 18Unittesting:http://guides.rubyonrails.org/testing.html#unit‐testing‐your‐models
[35] Unittestingfilesareusedfortestingmodels.Itmustbeincludedinthefirstlinerequire ‘testhelper’,giventhefactthatthefiletest_helper.rb,specifiesthedefaultconfigurationto runthetests.Aunittestexample: classCustomerTest<ActiveSupport::TestCase test"shouldinitializeattributes"do customer=Customer.new(:first_name=>'John',:last_name=>'Doe') assert_equal'John',customer.first_name assert_equal'Doe',customer.last_name end end Codesnippet10:UnittestwithtwoassertionsforaCustomerTestmodel Howtoexecutetests: Torununittestsfromtheconsole: raketest:units Foranindividualunittestfile: raketestTEST=path_to_test_file Tocallanspecifictestmethod: ruby‐I"lib:test"path_to_test_file‐nname_of_the_method" 3.5.1.3 Functional tests Functionaltests19aremeantfortestingvariousactionsofasinglecontroller.Some featureswhichshouldbetested: Successfulrequest.Therearefiverequesttypessupportedfortesting(get,post,put, headanddelete). Correctredirection. Successfulauthentication. Correctobjectstoredintheresponsetemplate.Afterarequesthasbeenmadeand process,thereexist4Hashobjectsfortheiruse: o assigns.Objectsstoredasinstancevariablesinactionsforusingviews. o cookies. o flash.Objectslocatedintheflash. o session.Objectslivinginsessionvariables Propermessagedisplayedtotheuserintheview,byassertingthepresenceofkey HTMLelementsandtheircontent. 19Functionaltests:http://guides.rubyonrails.org/testing.html#functional‐tests‐for‐your‐controllers
[36] Forfunctionaltestsarealsoavailablethreeinstancevariables,quiteself‐explainable: @controller,forthecontrollerprocessingrequest. @request,therequestitself. @response,theresponse. Thistaskwillbeexecutedforrunningfunctionaltests:raketest:functional 3.5.2Behavior‐DrivenDevelopment Behavior‐DrivenDevelopment(BDD)20isaspecializedversionofTDDwhichfocuses onbehavioralspecificationofsoftwareunitsandincludessomefeaturesfromDomain‐Driven Design(DDD)aswell. DDDfocusesonthestrengthsofobject‐orientedsoftwaredevelopmenttechniquesto simulatethecoreoftheproblem.Thus,itscorebuildsaproblemsimulationdomain, minimizingtechnicalinfluencesinordertomakemoreunderstandablebetweenusers, analystsanddevelopers.Thisaimisachievedusingacommonvocabulary,calledUbiquitous Language. Hence,BDDisacombinationoftwopowerfulapproachesforsoftwaredevelopment integratedintoone. Railsdoesn’tincludeaframeworktosupportBDD.However,thereexistafewlibraries whichmakeitpossible.Thereexistmorethanasinglealternative,butthesetoflibraries chosenforBDDinWaymateare: Cucumber21.Itletstodescribehowsoftwareshouldbehaveinplaintext.The textiswritteninabusiness‐readabledomain‐specificlanguageandservesas documentation,automatedtestsanddevelopment‐aid,allrolledintoone format. geminstallcucumber Webmock.It’salibraryforstubbingandsettingexpectationsonHTTPrequests inRuby. geminstallwebmock Capybara22.IthelpstotestRailsapplicationsbysimulatinghowarealuser wouldinteractwiththeapplication.Itisagnosticaboutthedriverrunning tests.WebKitissupportedthroughPoltergeist. geminstallcapybara 20Behavior‐DrivenDevelopment:http://en.wikipedia.org/wiki/Behavior‐driven_development 21Cucumber:http://cukes.info/ 22Capybara:https://github.com/jnicklas/capybara
[37] Poltergeist23.It’sadriverforCapybara.ItallowstorunCapybaratestsona headlessWebKitbrowser,providedbyPhantomJS. geminstallpoltergeist PhantomJS24.Ithasseveralfeatures,buttheoneinvolvedinthiscaseisSite Scraping.Themeaningofthisfeatureistoaccessandmanipulateweb‐pages withthestandardDOMAPI,orwithusuallibrarieslikejQuery. AllthefilesconcerningBDDwillbeunderthedirectoryfeatures.Thefiletoconfigure theenvironmentwheretheBDDwillexecuteisnamedenv.rbandlocatedunder features/support.Therelevantlinestoincludethelibrariesexplainedaboveare: require'cucumber/rails' require'webmock/cucumber' Capybara.default_selector=:css require'capybara/poltergeist' Capybara.javascript_driver=:poltergeist Codesnippet11:RequiredlinesforBDDlibrariesinclusionintheBDDtestingenvironment Oncetheselinesareincludedonthetopoftheconfigurationfile,dependingwhatis wanted,thisenvironmentcouldbeconfiguredinseveralways.It’sconsideredasnotnecessary tospecifyallthedetailsregardingthisconfiguration. BDDtestinginvolvesanimitationofservercontrollersinRailsandclientpages.There existthreekindoffiles: Fixtures,withtheaimofsimulatingrealdata,suchasresponses,object modelsandsoon.Theycanbefoundunder/features/fixtures. Stepdefinitionsarean analogoustoamethoddefinition/functiondefinitioninany kindofOO/proceduralprogramminglanguage.Theycantake0ormore argumentsareidentifiedbyRegexpmatching.Locatedinthe /features/step_definitionsfolder. Featuresdescribethestepsthatshouldhappenbeforethescenario’ssteps starttoexecute.Thesestepswillmatchwitharegularexpressiondefinedin thestepdefinitioninordertoexecutethecorrespondinglines. Scenariosarecomposedbystepsaswell.Theyaremeanttoimitateuser interactionoverdynamicpagescontainingJavaScriptcode. Featuresandscenariosaredefinedinthesamefile.Featuresareonlydefined ifsomepreconditionsareneededbeforeexecutingthescenario’ssteps.These filesarelocatedunder/featuresdirectory. 23Poltergeist:https://github.com/jonleighton/poltergeist 24Phantominstallationguide:http://phantomjs.org/download.html
[38] AnexampleofaScenariowithitscorrespondingStepdefinitionsbelow: @javascript Scenario:Login GivenIamauser AndIamontheloginpage WhenIlogin ThenIshouldbeonthesearchpage Codesnippet12:Scenarioexample Given/^Iamauser$/do name="user#{rand(Time.now.to_i)}" @user=User.create!(:login=>name,:password=>'password',:password_confirmation=> 'password',:email=>"#{name}@email.com") end Given/^Iamontheloginpage$/do visitlogin_path(:locale=>'en') end Given/^Iamaloggedinuser$/do step"Iamauser" step"Iamontheloginpage" step"Ilogin" end When/^Ilogin$/do fill_in'user_session_login',:with=>@user.login fill_in'user_session_password',:with=>@user.password click_on'ANMELDEN' end Codesnippet13:Stepdefinitionsforascenario
[39] 3.6.AssetPipeline Theassetpipeline25providesaframeworktoconcatenateandcompressJavaScriptand CSSassets.Inproductionisessentialtoincludesuchframework,dueitreducesthenumberof requeststhatcanbemadeinparallel,increasingthespeedloadingtheapplication. RailsisintegratedwithalibrarycalledSprocketswhichprovidesthisfunctionality.By defaultisenabled,butifit’sneededtobedisabled,inconfig/application.rb: config.assets.enabled=false 3.6.1Fingerprinting Intheproductionenvironment,RailsinsertsanMD5fingerprint,intoeachfilename andthefileiscachedinthebrowser.Fingerprintingisatechniquewhichmakesthenameofa filedependentonthecontentsofthefile,henceifthecontentchangesthefingerprintwill changeaswell.Besides,HTTPheaderscanbesettoencouragecachestokeeptheirowncopy ofthecontent,reducingtherequests. 3.6.2Location Assetsindevelopmentshouldbeplacedunderapp/assetsfolder.Inproduction,Rails precompilesthesefilesandplacesthemunderpublic/assetsdirectory,wherethecopieswith thefingerprintincludedarethenservedasstaticassetsbythewebserver. 3.6.3Assetsinclusionfortheirusage AssetsarelinkedfromtheHTMLlayoutortemplatefiles.WithintheHTMLtag<head> </head>mustbeaddedthefollowinglines,specifyingthenameofthefilewithoutits extension: Cssfiles:<%=stylesheet_link_tag"stylesheet1",“stylesheet2”%> JavaScriptfiles:<%=javascript_include_tag"javascript_file1",“javascript_file2”%> Sprocketsusesmanifestfilestodeterminewhichassetstoincludeandserveoverthe entireapplication.Manifestfilescontaindirectiveswhichtellthefilestorequireinorderto buildaCSSorJavaScriptfile.Itisverycommontohaveauniquefileunderthedirectory app/assets/javascriptsnamedasapplication.jswhichcontainsallthenecessarydirectivesto precompiletheassets.Intheapplicationthisfilelookslikethis: 25Assetpipeline:http://guides.rubyonrails.org/asset_pipeline.html
[40] //Librariesrequired //=requirejquery //=requirejquery_ujs //=requirejquery‐ui //=requireunderscore //=requirebackbone //=requiremustache //Filesrequired //=requireapp //=requireapp_router //=require_tree./lib //=require_tree./models //=require_tree./views //=require_tree./collections Codesnippet14:JavaScriptfilesinclusionintheprojectfromtheapplication.jsfile AsJavaScriptfilescontainsjQuery,Backbone,MustacheandUnderscoremethodsmustbe placedbeforerequiringtheJavaScriptfileswhichmakeuseofthem.Thesixformers//=require includethelibraries(whichwillbeexplainedintheclienttechnologiessection). TheotherlinesspecifytheJavaScriptfileswhichusethementionedlibraries.Thesesetof //=requirelinesexplainactuallyhowthefoldersandfilesareorganizedwithin app/assets/javascriptsdirectory. app/ assets/ images/ javascripts/ collections/ lib/ models/ views/ app.js app_router.js application.js stylesheets/ Codesnippet15:JavaScriptfilesorganization Thereby,beforeservingtheassets,theselibrariesmustberequired,otherwise,itwon’t identifytheirmethodsandwillproduceseveralerrors.
[41] 3.6.4Compressionlibraries ForCSSfilesthereexistsagemcalledYUIwhichprovidesminification,removingall unnecessarycharactersfromthesourcecodewithoutchangingthefunctionality. ForJavaScript,thereareseverallibraries,buttheonewhichobtainsbetter performanceisUglifierandit’salreadyincludedinthedefaultGemfile.Itprovidesminification andotheroptimizations. 3.6.5Environmentconfiguration It’scrucialtohaveconfiguredtheassetsproperlyfortheproductionenvironment, giventheenhancedperformancethatcanprovidetotheapplication. Inconfig/environments/production,theselineswillbenecessarytocompresstheCSS andJavaScriptlibrariescommentedpreviously: config.assets.compress=true config.assets.css_compressor=:yui config.assets.js_compressor=:uglifier Codesnippet16:Compressionlibrariesinclusionintheproductionenvironment Tospecifytheassetstobeprecompiled,thenameofthefiles,accompaniedwiththe extension,mustbeincludedwithinthebracketsofthefollowingcommand: config.assets.precompile+=%w(<assetsinclusion>) Ifthereismissingasinglefileinthissection,theapplication,intheproductionenvironment, willfailwhenisneeded. Forgettingfingerprintingenabled: config.assets.digest=true Aslivecompilationisnotneededinthisapplication,whichwoulddecrease substantiallytheperformance,so: config.assets.compile=false
[48] Theyarenotreferencedactually.Togetthechangesbackagaingitreflog 4.2.2.5Rebasing Combineadeterminenumberofcommitsintoone. gitrebase–iHEAD~<number> Rebasingbranches.Torewritehistory,sothatitlookslikeabranchwasoriginated fromanothercommit. gitcheckout<branch_name> gitrebasemaster Ifthere’saconflict,rebasestops.Conflictsmustbesolved,changescommittedandthe run. gitrebase‐‐continue Tocanceltherebaseifaconflictoccurs. gitrebase‐‐abort ThereactuallyexistmoreadvancedtopicsandcommandswhichGitsupports. Nevertheless,withtheonespreviouslycommented,adeveloper’steamhaveanadvance controlandgoodmanagementovertherepositorywheretheydevelopsimultaneously. 4.2.3.Conflicts Severaldevelopersworkingconcurrentlyinthesameprojectrequirecoordinationin thedeploymentprocess.Sometimesitisnecessarythatdevelopersprogramdifferent functionalitiesinthesamefilessimultaneously.Thisfactcouldcauseconflictsmergingthese filesinthelocalversionsoftheapplicationwhichhaveeachdeveloper.Fortunately,GitHub helpstosolvethisproblem.Itcontainsanalgorithmwhichtriestomergeautomaticallythose filesthathavebeenmodifiedfordifferentdevelopers. Thisalgorithmdoesn’tworkalways,duetoitonlyworkswhendifferentmodulesor functionsforaspecificfilehavebeenmodified.Thiscasehappenswhensomespecificlinesof thecodehavebeenmodifiedbytwoormoredevelopersandthechangeshaven’tbeenpulled beforestartingtomodifythatsnippetofthecode.Hence,whenanewversionfromaworking copyiscommittedandpulledafterwards,inordertogettheupdatedversion,thelocalversion oftheapplicationgetsaconflictwhichhastobefixedmanually.Oncetheconflictsarefixedby thedeveloper,thechangescouldbecommitted.Thenanotherpullisrequiredtomergethe fileswhichcontainedconflictspreviouslyandthereupon,thesecommitswillbepushed, updatingtoanewversionthehostedrepository.
[49] 4.3.Capistranodeployment Capistrano26isanopensourcetoolforrunningscriptsonmultipleserverssuchasthe casewhichconcernus,todeploywebapplications.Itautomatestheprocessofmakinganew versionofanapplicationavailableonawebserver. ItiswritteninRubyanddistributedusingtheRubyGems.Togetitinstalledasrails gem,it’sjustneededtotypegeminstallCapistrano.Toconfigureit’snotstraightforward.ss TheuseimplementationisbyBashcommandline.Thisframeworkincludesthe executionofcommandsinparallelonmultipleremotemachinesviaSSH.Itusesasimple domain‐specificlanguage(DSL),programminglanguagededicatedtoaparticularsolution technique. Itsimplifiesandautomatesthedeploymenttodistributedenvironmentsandcome bundledwithasetoftasksdesignedfordeployingRailsapplications. Italsoincludessupportingtaskssuchas: Databasesmigrations.Ifanewreleasehassomependingmigrations,theycan berunontheserver. capdeploy:migrateorcapdeploy:migrations Migrationscouldbeconfiguredtobeexecutedafterthecodeisupdatedon theserverautomaticallybyaddingthislinethefiledeploy.rb: after‘deploy:update_code’,‘deploy:migrate’ Startandstoptheapplicationservers. capdeploy:start capdeploy:stop Assetpipelineprecompilation.In./Capfileshouldbethislineincluded load‘deploy/assets’ Cleaning‐upoldreleases. capdeploy:cleanup Rollbackdeploymentofthepreviousversion. capdeploy:rollback Debuggingdeploymentswhichfailed capdeploy‐d Testdeploymentdependencies,whichchecksdirectorypermissions, necessaryutilitiesandreportsthingsthatappeartobeincorrectormissing. capdeploy:check 26Capistranoguide:https://gist.github.com/2161449
[50] Copytheprojectandupdatethesymlinktothemostrecentlydeployed version.Thesymboliclinkisaspecialfilewhichcontainsareferencetothe directoryintheformofanabsoluteorrelativepath. capdeploy:update Toupdatethesymlinkexplicitly,whichwillberarelyexecuted. capdeploy:symlink Toconfigurethistoolisnotquitestraightforward.OnceCapistranoisalreadyinstalledin thelocalmachine,thesearethestepstoconfigureitproperly: 1) SetupSSHaccess.ToallowCapistranotologintotheOCSserverandruntheproper commands,theeasiestwayisbygeneratinganSSHkey. 2) Server‐sidepreparations: a. RequestaportforMongreltolistenon.Mongrelisalibraryandwebserver writteninRubytorunwebapplicationsandpresentsastandardHTTP interface. b. CachetheSVNcredentials.Everytimeanewversionisdeployedwiththis framework,itchecksoutanewversionfromtheSubversionrepository.To makethisprocesswork,ithastobecheckeditoutmanuallyontheserver. Hence,thecredentialsusedarecachedanditwon’tcauseanyproblem afterwards.Tocheckoutmanuallythefollowingstepshavetobefulfilled: i. LogintotheremoteserverviaSSH. ii. Checkoutacopyofthetrunk. svnco–usernameUSERhttp://svn.domain.com/path/to/repo/trunk iii. Letitruntilltheentirethingischeckedoutandthendeletethefolder rm–rftrunk/ 3) Capifytheapplication ToaddCapistranosupporttotheapplicationthenextstepsshouldbefollowedafter typingintheterminal: capify. a. Customizethedeploymentrecipe.Thefileconfig/deploy.rbwhichCapistrano hasaddedtotheapphastobecustomizedtogetitconfiguredforthe application.Inthisfilehastobespecifiedthingssuchas: i. Repositorylink. ii. Portnumber. iii. Websitemonitoringsystemcallback. iv. Differentstages. Andotherdifferentfeaturestomakeitworkproperly.Herethedeveloperhas kindoffreedombecausehecouldconfigureitdifferently. b. Setuptheremotedirectorystructure.Thisactionwillautomaticallyloginto theOCSserverandcreateanewfolderwithnamespecifiedunder set:deploy_to.Inthisfoldermustbecreatedthefolders“releases”and
[51] “shared”.Furthermore,thefiledatabase.ymlshouldbecreatedintheserver side,whichisthedatabaseusedbytheapplicationhosted. 4) Deploythewebsite.Fordeployingthefirsttimeit’snecessarytodeploya‘cold’ application.Itwilldeploythecode,runpendingmigrationsanditwillinvokedeploy:start tofireupapplicationservers. capdeploy:cold 5) Testthedeployedwebsite.InordertomakesurethatMongrelisservingupthe websitecorrectly,inabrowsercouldbeopenedwiththisurl http://website.com:60040.IftheRailsapplicationappears,everythingwentright. 6) Settingupaproxyforthewebsite.Fornotreferencingthesitebyportnumberfor anythingotherthantestitisnecessarytoproxytheMongreltothewebsite.Tohave thewebsitegototheRailsappwithouttheport,itneedstobecreatedthe.htaccess fileinthepublic_htmlfolderandplacethiscodechunkinside: RewriteEngineon RewriteCond%{HTTP_HOST}^www.domain.com$[OR] RewriteCond%{HTTP_HOST}^www.domain.com$ RewriteRule^(.*)$htpp://127.0.0.1:port_number%{REQUEST_URI}[P,QSA,L] Codesnippet18:TemplatetoproxytheMongrelwithawebsite 7) StartingtheapplicationonReboot.OncetheMongrelinstanceisrunning,it recommendedmakingsurethatgetsstartedagainiftheserverhastoreboot.
[52] 4.4.Multistage Astageisaversionoftheweb‐hostedapplicationrepositorywhichcanbeaccessed fromthebrowser.Itisrecommendedtohaveatleasttwodifferentstages,oneforthelive system,so‐calledproductionstage,thatuserswillaccessandtheotheronefortesting,which isnamedstaging. Developersalwayshaveaccesstothelatestversionoftherepositoryintheirlocal repository.Fromtimetotime,thenewestversiondevelopedsofarit’sdeployedonstaging.As otherteammembers,whoarenotdevelopers,wanttohaveaccessandseehowthe developmentprocessisgoinginthehalfwayofgettinganewfeaturewhichisalreadynot deployedinthelivesystem,theycouldaccesstothestagingserver,witharelativenewversion andevaluatetheprogresstotakedeterminedecisionsintheirwork.Hence,thestagingserver itismainlyusedforlettingotherteammemberstestthecurrentstateofthedevelopment processtowardstheversionthatwillbeliveeventuallywiththenewrequiredfunctionalities. Oncethenewfeaturesdevelopedforthewebapplicationhavebeentestedbythe entireteam,includingnotdevelopersaswell,andnobugsaredetected,thenewversionis deployedonthelivesystemandaccessibletotheusers. Capistranoprovidessupporttomultistagewithaseparateextension.Itisneededto installanadditionalRubyGemwhichisintegratedinthesystembytypinggeminstall capistrano‐ext Toconfigurethismultistagefeatureitwouldbenecessarytoaddin“config/deploy.rb” thesecommandlinesforhavingthestagingandproductiondifferentstages: set:stages,%w(productionstaging) set:default_stage,“staging” require‘capistrano/ext/multistage’ Codesnippet19:Multistagingconfigurationfortwodifferentstages Afterwards,underthefolderconfig/deploywillbeallocatedthefilesproduction.rband staging.rbwherethecustomstage‐specificcodewillbeplaced. Finally,fordeployingintheproductionstageit’sneededtotypeintheconsole capproductiondeployandtofollowsuitforthestagingcapstagingdeployorcapdeploy,as stagingisthedefaultstage,specifiedinthelinetwoofthesnippetabove.
[53] 4.5.Testingbeforedeploying Itisn’tpossibletoguaranteeacompletelyversiondeploymentwhichwillworkwithout triggeringanexception.However,itispossibletoenhancethereliabilityoftheprocessby testingtheapplicationbeforethedeploymentfromthelocaltothehostedrepositoryand fromthehostedrepositorytotheliveversionwhichtheusersaccessfromtheirbrowsers. Onceadeveloperdecidestodeploytheversionwhichisinthehost‐basedrepository, executescapproductiondeploy.Nevertheless,thisnewversionisnotdeployedinstantly,dueto itshouldbeensuredtopasstestsbeforehavingthefreshversiononthelivesystem.To achievethispurpose,Jenkinstriggersalltheexistingtests. UnitandFunctionaltestsfortheserver‐side. Unittestsfortheclient‐side. Behavior‐Driventestsforboth,clientandserver‐side. Inordertodeploythelatestversion,allthetestsshouldpass.Incaseofasingletestfails, thecorrespondingcodeshouldbefixed,changespushedtothehost‐basedrepositoryand thendeploythenewversionagain. Jenkins27isanopen‐sourcecontinuousintegrationservicestoolforsoftwaredevelopment. Itisaserver‐basedsystemrunninginaservlet,Java‐basedserver‐sidewebtechnology.It supportsrevisioncontrol(SCM)suchasGit. 27Jenkinsguide:https://wiki.jenkins‐ci.org/display/JENKINS/Use+Jenkins
[54] 4.5.Websitemonitoringsystem Howadevelopercouldknowthattheapplicationwhichrunsonthelivesystem doesn’ttriggeranyexception? Evenafterallthetestingbeforegettingthenewversionrunningonlivecouldbe somethingwhichstillcouldfail.Inordertokeeptrackoftheexceptionsproducedinthe websiteapplication,thesystemmustbemonitored. TinyMon TinyMon28isafull‐stackwebsitemonitoringsystem.Whilemonitoring,itsimulatesa webbrowserandperformscomplexconfigurablesteps. Itdoesn’tmonitortheindividualcomponentsthatbuildupthewebsite.Instead,it takestheuserperspectiveandtestswhetherallcomponentsareworkingtogethertogenerate theexpectedbrowsingexperience.Itisn’tareplacementofsoftwaretest,butanimportant addition. Featuresincludedinthisframework: Fillinloginformsandloginusingatestaccount. Completetransactionforonlineshopping. Monitorthesignupprocess. Monitorexternalwebsitesorservicesthesystemdependson. Tosetthiswebsitemonitoringtoolupfortrackingtheapplicationthesearethesteps thatshouldbefollowed: 1) Createanewaccount.Anewaccountrepresentsaclusterofwebsitesbelongingto thesameclient.ItholdstheaccessrightstositesandHealthCheckswithinsites.A userthatisgivenaccesstoanaccountcanalwaysseeallsitesandcheckswithinthis account. 2) Createanewsite.ItprovidesabaseURL,soasubdomainwouldbeanewSiteunless it’sprovidedafullpathinvisitstepsforHealthChecksforaSitessubdomain.The cleanwayistotreatsubdomainslikeanewSite. 3) CreateanewHealthCheck.Itcanbechoseneitherfromafewpredefinedtemplates orcreateafirststepfromthescratch.Inthetemplatemustbeprovidedapathforthe visitstepandastringforthecheck‐contentstep. 4) TestdrivefortheHealthCheck.It’sjustneededtoclick“Information”andthen“Run”. Afterawhilethepageshouldberefreshedorclick“Checkruns”toseehowthetests workedout.Iftestspassed,thecheckcanbeenabled. 28TinyMon:http://www.tinymon.org/pages/faq
[55] 5) Integrateitintheapplicationcode.Thissnippetmustbeaddedinthefile config/deploy.rb: 1 task:markdo 2ifstage=='production' 3callback_url= 'http://mon.tinymon.org/deployments/510478e487b921349e0599bfb64fef45' 4system"curl‐Fdeployment[revision]=#{current_revision}‐F deployment[schedule_checks_in]=3#{callback_url}" 5end 6end Codesnippet20:IntegrateTyniMonintheproductionstage Thesecondlinespecifiesthatthecallbackitisonlyexecutedfortheproductionstage, whichistheoneusedforthelivesystem.Thefourthlinesetsthedeploymentrevisionfor whichthecallbackshouldbeexecuted. Forsendingemailstoallteamofdevelopers,inconfig/environment/production.rb,it’s beenincludedthischunkofcode: config.middleware.useExceptionNotifier, :email_prefix=>"[Exception]", :sender_address=>%{"ExceptionNotifier"<
[email protected]>}, :exception_recipients=>%w{
[email protected]} Codesnippet21:ExceptionNotifierconfiguration Theselinesspecifythesubject,thesenderandtheaddresstobesentwhenTinyMon detectsanexception. Tosetthisusefulandimportanttoolup,itisquitestraightforwardandprogrammingskills arenotneededatall.Oncethisframeworkiscompletelysetup,ifanerroroccursonthelive system,everydeveloperwillreceiveanemailwithanerrordescriptionaboutwhatitfailed. ThisfunctionalityisintegratedbyExceptionNotifierPluginforRails,whichprovidesa mailerobjectandadefaultsetoftemplatesforsendingemailnotificationswhenerrorsoccur. Bydefault,thenotificationemailincludestherequest,session,environmentandbacktrace. Nevertheless,eachofthosesectionscanbecustomizedrenderingapartialwiththenameof thepartthatwantstobemodified(e.g.,_session.html.erb)underthefolder app/views/exception_notifier.Theinformationavailablefromthesepartialsisthefollowing: @controller:thecontrollerthatcausedtheerror. @request:thecurrentrequestobject. @exception:theexceptionthatwasraised. @backtrace:asanitizedversionoftheexception'sbacktrace. @data:ahashofoptionaldatavaluesthatwerepassedtothenotifier. @sections:thearrayofsectionstoincludeintheemail.
[56] 5.APIsdataabstractionintoacommonobject DatathatcomesfromdifferentAPIstorepresentconnectionsfordifferentmeansof transportationorcompaniesisprovidedindifferentformats,structuresandattributes.Thisis aproblem,becausehavingdifferentobjectmodelsforeachAPImakestheback‐endeven moredifficulttomaintainandtest.Maintenancegetsmorecomplicatedduetodifferent objectmodelshavetobetreatedwithdifferentlogic.ConsideringthatinthefuturemoreAPIs willbeincluded,thisfactimpliesadditionallogicforthefunctionalityachievedsofar, specificallyforthenewobjectmodel. Therefore,havingasingleobjectmodelwhichencompassesintoonethedatathat comesfromdifferentAPIspresentsthefollowingadvantages: Savescodeduplication,duethedeveloperonlyhastomakethenewobjectmodelfit intheglobal. Functionsaremoretestable.Havingdifferentobjectsthecodeincludesalotof comparisonif‐else,whicharenotsoeasytotest. Theprojectremainsbetterstructured. Thecodeiscleanerandhence,morereadable. Intheoldapproachtrainsandflightsweredifferentobjectmodels,butit’sbeenmanaged toconvergethesetwodifferentobjectsintoaflexibleandconsistentsingleobjectmodel. Probablyitseemstobeeasy,becausealotofattributesaresharedsuchasorigin,destination, departure,timeandsoon.Themaindifficultywasfoundatthetimetocreateasub‐objectfor tariffsandprices. ForeachAPIwherethedataisretrieved,anindependentfileisneededtoparsethe responseandtransformitintoacommonobjectmodel.Regardingthedatastructuretostore alldifferentpossibilitiesandtheglobalconnectionobjectmodelisconfidential,sonomore furtherdetailswillbeexplained. Waymateofferstravelsolutions,connectingcitiesalloverEuropeandsomecities outsidetheboundariesfromtheoldcontinent.Theseconnectionsarecoveredbytrainand flights.But,fromwhichAPIsdoesthisdatacomefrom? 5.1.DeutscheBahnAPI DeutscheBahnAG(DB)isthebiggestGermannationalrailwaycompany.Theyoffer connectionsbytraingivingfullcoverageoverGermanyandsomeimportantcitieswithin Europe.However,destinationororiginmustbeaGermancity,implyingthatthereisnotrain connectionwhichlinkstwocitiesasoriginanddestinationouterfromGermany. DBBahnhasopeneditsAPItoWaymate,providingallthedetailsinformationfor differentconnectionstotravelinadeterminedate,fromoneplacetoanother.Togetaccess tothisAPIWaymateandDBformalizedacontract,providinginthefirstinstanceaccesstoa testingserver.Afterbeingdevelopingwiththetestingserver,DBtesttheapplicationandif
[57] thereisnobugsoranincorrectwayintheprocess,suchashowtoshowtheconditions,the realAPIisopened. Foreachrequestisneededtoincludeauser,passwordandkey(providedbyDBafter signingacontract)inthebodyofeachrequestandbesidestwoXMLfilestemplatesfilledwith theproperattributestocomposetherequest.Toguaranteetheencryptionofconfidential information,suchascreditcardnumbers,theprotocolHTTPSisusedforsendingthis information.ThisprotocoladdsthesecuritycapabilitiesofSSL/TSLtothestandard.The responseofthisAPIforadetermineconnectionincludes: Trainschedules.Inordertoconnecttwodifferentcities,thereisnotalwaysadirect train,hence,someconnectionscontainmorethanonetrainschedule,makingoneor morestopoversinothercities.Eachschedulecontains: o Arrivalanddeparturetimeanddate. o OriginanddestinationtrainstationsnameandEVA(uniquetrainstation identifier). o Traincategoryandnumber. Asetofschedules(orasingleoneifthereisadirecttrain),composeaconnection.A connectionincludestheelementofferwith: o Totalprice. o Offercodeanditsdescription. o Class(1stor2nd). o Codesforlong‐distancetrains. o Typesofpossiblepayments. 5.2.YpsilonAPI YpsilonisacompanywhichprovidesaccesstoitsInternetBookingEngine.ItsAPI providesflightconnectionscoveragebetweencitiesalloverEurope,includingseveralairlines. ItalsocanprovidesomeconnectionsfromEuropetoothercontinentortheotherwayaround, aswellasmulti‐currencytohandlethebookingprocessfortheseflights. Alltheprocessregardingthecontractandstartinggettingdatafromatestingserver followsthesamelogicthanwithDB,soisnotnecessarytorepeatitagain. Forsendingrequestsit’sneededtoincludeanauthorizationcodeinthebody,withthe nameofthecompanyfollowedbyacodeprovidedbyYpsilon,specifyaport,asecureport,a host,asecurehostandaclientcertification.It’ssentbyHTTPSaswell,buttheencryptionit’s strongergiventheclientcertificationusage.
[64] 6.3.Dynamicweb‐site WithHTMLandCSSstaticweb‐sitescanbebuiltup,howeverthereisnologicincluded andlimitedinteraction.Inordertoincludedataprocessingwithitscorrespondinglogicand userinteraction,thefollowingtechnologiesareincludedintheproject. 6.3.1.JavaScript JavaScript(JS)32isaprototype‐basedscriptingandmulti‐paradigmlanguage,supporting object‐oriented,imperativeandfunctionalprogrammingstyles.It’sdynamic,weaklytyped (supportingimplicittypingconversionandprovidingalotofflexibilitywhenoperatingwith differenttypes)andhasfirst‐classfunctions.ItssyntaxisinfluencedbyCandJava,butboth areactuallyunrelatedandhaveverydifferentsemantics. JavaScriptdoesn’thaveclasses,insteadusesprototypes,whichcansimulatemanyclass‐ basedfeatures. It’smainlyusedforprogrammingclient‐sidesforwebpagesandapplicationsandcan respondtouseractionquickly,makinganapplicationmoreresponsive. JavaScriptisimplementedaspartofaWebbrowser,whichworksasarun‐time environmentitself,providingobjectsandmethodsbywhichscriptscaninteractwiththe “outsideworld”inordertogiveenhanceduserinterfacesanddynamicwebsites.Thefunctions areembeddedinHTMLpagesandinteractwiththeDocumentObjectModel(DOM),cross‐ platformandlanguage‐independentconventionforrepresentingandinteractingwithobjects inHTML,XMLandXHTMLdocuments.Inaddition,isabletodetectuseractionwhichHTML cannotdobyitself,suchasindividualkeystrokes. 6.3.2.AJAX AsynchronousJavaScriptandXML,commonlyknownasAJAX33,isagroupof interrelatedwebdevelopmenttechniquesusedontheclient‐sidetocreateasynchronousweb applications.Therefore,webapplicationscansenddatato,andretrievedatafrom,aserver asynchronously(inthebackground),withoutinterferingwithdisplayandbehaviorofthe existingpage.DatacanberetrievedusingtheXMLHttpRequestobject,however,despitethe name,theformatoftenusedisJSON. Thistechnologyenhancestheuserinteractionalongtheapplication,avoiding unnecessaryfullpagesreloads,duetoXMLHttpRequestobjectprovideamethodfor exchangingdataasynchronouslybetweenbrowserandserver. 32JavaScript:http://en.wikipedia.org/wiki/JavaScript 33AJAX:http://en.wikipedia.org/wiki/Ajax_(programming)
[65] 6.3.3.jQuery jQuery34isamulti‐browserJavaScriptlibrarydesignedwiththeintentiontosimplify theclient‐sidescripting.It’sthemostpopularandusednowadays,dueitallowsthecreationof powerfuldynamicwebpagesandwebapplications. Itssyntaxmakeseasytonavigateadocument,selectDOMelements,create animations,handleelementsanddevelopAjaxapplications.Italsoprovidescapabilitiesto extenditsfunctionalitycreatingplug‐insontopoftheJavaScriptlibrary,sodeveloperscan createabstractionsforlow‐leverinteraction,advancedeffectsandanimations. ToincludethisJavaScriptlibrary,oranotherone,intotheprojectit’snecessaryto includethislinebetweentheheadtags. <head> <scripttype="text/javascript"src="jquery.js"></script> </head> Codesnippet25:JavaScriptlibraryinclusionfromaHTMLtemplate ThewaytointroduceajQueryfunctionistousethe.ready()function.Then,whenthe pageisloaded,thecodewithinthissectionwillbeexecuted.Functionswillbedefinedoutof it. $(document).ready(function(){ //codegoeshere }); ToaccessandmanipulateDOMnodesjQueryprovidesthe$function.Itiscalledwitha CSSselectorstringfortheclassoridoftheDOMelement,resultinganobjectreferenceafter thematching. $(‘#navigation.element’).addClass(‘selected’); Thislineaddtheclass“selected”toallchildrenDOMelementsundertheonewithid “navigation”whichcontaintheclass“element”. Thislibraryprovidesalargesetofmethodsfor: SelectingDOMelementsandmanipulatethem. Gettingandsettingattributesforinputelementssuchascheckboxes,input fields,radiobuttonsanddropdownlists. GettingandsettingtheCSSstylingforHTMLelements. Eventsmethodswhichregisterbehaviorstotakeeffectwhentheuser interactswiththeelementsandmanipulatethoseregisteredevents. 34jQuery:http://en.wikipedia.org/wiki/Jquery
[66] Visualeffectsforaddinganimationtoawebpage,fromsimplestandard animationstosophisticatedcustomeffects. AJAXcapabilities,toallowloadingdatafrom/totheserverwithoutbrowser pagerefresh. ThereexistsastandardbundleofjQuerylibrarytointeractwithUIelements.Inthis application,theDraggableplugin,whichmakesselectedelementsdraggablebymouseis included. Regardingwidgetplugins,theonesincludedare: Datepicker,aconfigurableandcustomizablecalendartoselectspecificdates orrangedates. Slider,whichmakesselectedelementsintosliderandprovidesvariousoptions suchasmultiplehandlesandranges. 6.3.4.Backbone Backbone35isaJavaScriptframeworkbasedonthemodel‐view‐controller(MVC) applicationdesignparadigm.Itisdesignedfordevelopingsingle‐pagewebapplications(SPA) andforkeepingvariouspartsofwebapplicationssynchronized.Itgivesstructuretoweb applicationsbyprovingmodelwithkey‐valuebindingandcustomevents,collectionwitha completeandusefulAPIoffunctions,viewswithdeclarativeeventhandling,andconnectsitall totheserverAPIthroughaRESTfulJSONinterface. WithBackbone,JavaScriptfilesmustbefollowaspecificorganization,divingplacing themundermodels,collections,helperlibrariesandviewsfolders.Havingagoodfiles organizationwillhelptofindfilesfasterandmaintainthem. app/ assets/ images/ javascripts/ collections/ lib/ models/ views/ app.js app_router.js application.js Codesnippet26:Backbone.JavaScriptfilesorganization 6.3.4.1.ImportanceofusingaMVCframeworkinthefront‐end TheentireapplicationinvolvesalotofJavaScriptcodeandthisgenerallyimpliestoend upwithtangledpilesofjQueryselectorsandcallbacks,alltryingtokeepdatain synchronizationbetweentheHTMLUI,JavaScriptlogicandtheserverdatabase.Nevertheless 35Backbone:http://backbonejs.org/
[67] itisnotrecommendedtotiethedatatoDOMelementsandforrichclient‐sideapplications,a morestructuredapproachishelpful. BackbonerepresentsthedataasModels,whichcanbecreated,validateddestroyed andsavedtotheserver.ItalsoprovidesViewsthatdisplaysthemodel’sstateandcanbe notifiedofthechangeofthemodelinordertobeabletorespondandre‐rendertheviewfor thenewmodeldata.Hence,intheenditwon’tbenecessarytowritethecodethatlooksinto theDOMtofindanelementwithanidandupdatetheHTMLmanually,giventhatwhenmodel changes,theviewsupdatesbythemselves. Theadvantageofhavingasingle‐pagewebapplicationistoprovideamorefluiduser experience,duetochangesareperformedloadingnewcodeondemandfromthewebserver, drivenbyuseractions.Continualpageredrawsdisrupttheuserexperienceduetothenetwork latenciescannotbehidden.Thepagedoesn’tautomaticallyreloadduringuserinteractionwith theapplication,thereforenounnecessarydatare‐transmitionitisperformance.Thetechnique whichallowsthiscontinuousandfluiduserexperienceisAJAX,allowingasynchronous communicationbetweenclientandserver. 6.3.4.2Comparisonwithsimilarframeworks AlotofMVCframeworksforJavaScripthavecomeuplately.Themostfamous frameworks,inadditiontoBackbone,areSpine,AngularJSandEmber. Actuallythereisnobestchoiceamongthese4alternatives,duetheyofferthesame interestingfeaturesforsuchkindofframework,butinwithdifferentsyntax. So,howtoselectthebestchoice? WaymatedeveloperswereaskingthroughtheRailscommunityinordertofinda unanimousanswer.However,itdidn’thappen,differentdeveloperswerepromotingdifferent frameworks. ThesecondideawastoaskinaRubyconference,wherealotofprestigiousRubyon Railsprogrammersusetoattend.IthappenedthesameasintheRailscommunity. So,finally,WaymatedevelopersdecidedtochooseBackboneforthreereasons: It’swelldocumented. Theclient‐sideofprestigiousprojectshavebeenbuiltupusingthisframework. It’sthemostpopularamongallthealternatives.
[68] 6.4.3.3.Backbonecomponents 6.4.3.3.1 Backbone.sync Backbone.syncisthefunctionthatBackbonecallseverytimeitattemptstoread orsaveamodeltotheserver.Bydefault,ituses(jQuery/Zepto).ajaxtomakeaRESTfulJSON requestandreturnsajQueryXMLHttpRequestobjectby$.ajax(jqXHR). sync(method,model,[options]) Themethodcouldbeeithercreate,read,updateordelete. Themodeltobesavedorcollectiontoberead. Theoptionsaresuccess,errorcallbacksandotherjQueryrequestoptions ThismethodcouldbeoverriddengloballyasBackbone.sync,oratafiner‐grained level,byaddingasyncfunctiontoaBackbonecollectionortoanindividualmodelforusinga differentpersistencystrategysuchasWebSockets,XMLtransportorLocalStorage. Thedefaultimplementationsendsuparequesttosaveamodel,itsattributeswillbe passed,serializedasJSONadsentintheHTTPbodywithcontent‐typeapplication/json.When aJSONresponseisreturned,senddowntheattributesofthemodelthathavebeenchanged bytheserver,andneedtobeupdatedontheclient.Furtheron,itwillbeexplainhowcouldbe fulfilledbymeansofaBackbone.Model. ThedefaultsynchandlermapsCRUDtoRESTlikeso: create‐>POST/collection read‐>GET/collection[/id] update‐>PUT/collection/id delete‐>DELETE/collection/id 6.4.3.3.2 Backbone.Events Backbone.Eventsisamodulethatcanbeassociatedtoanyobject,givingtheabilityto bindandtriggercustomnamedevents.Theydon’thavenecessarilytobedeclaredbeforethey areboundandcantakepassedarguments. Acallbackfunctioncouldbeboundtoanobject,soitwillbeinvokedwheneverthe correspondingeventisfired. object.on(event,callback,[context]) Tosupplyacontextvalueforthiswhenthecallbackisinvoked,inthethirdargument [context]shouldbepassedthis. Callbacksboundtothespecialalleventswillbetriggeredwhenanyeventoccursand arepassednameoftheeventasthefirstargument.
[69] Removeapreviously‐boundcallbackfunctionfromanobject: object.off([event],[callback],[context]) Ifnocontextisspecified,alloftheversionsofthecallbackwithdifferentcontextswill beremoved.Ifnocallbackisspecified,allcallbacksfortheeventwillberemovedand obviouslyifnoeventisspecified,alleventcallbacksontheobjectwillberemoved. Triggeringcallbacksforthegivenevent,orspace‐delimitedlistofevents. Furthermore,subsequentargumentstotriggerwillbepassedalongtheevent callbacksseparatedwithcomas. object.trigger(event,[*args]) 6.4.3.3.3 Backbone.Model Modelscontaintheinteractivedataaswellasalargepartofthelogicsurroundingit suchasconversions,validations,computedpropertiesandaccesscontrol.ABackbone.Model providesabasicsetoffunctionalityformanagingchanges.Nevertheless,tocreateanewone shouldbeextendedwiththeirownspecificmethods. TocreateacustomizedModelclass,Backbone.Modelshouldbeextendedandinstance propertiesprovided.Hence,thedefinitionofanewmodelwithitsownfunctionsshouldlook somethinglikethis: varname_model1=Backbone.Model.extend({ initialize:function(){…}, name_function1:function(){…}, name_function2:function(param1,param2,..){…} } Codesnippet27:Backbone.Modeldefinition Accordingly,extendcorrectlysetsuptheprototypechain,sosubclassescreatedwith extendcanbefurtherextendedasfarasadeveloperwants. varname_model2=name_model1.extend({…}) Whenamodelinstanceiscreated,optionalclassPropertiescanbeattacheddirectlyto theconstructorfunction. newModel([attributes]) Theseattributescouldbeasimpleattribute,anarrayorevenanothermodel,which willbesetonthemodelinwhichhavebeenpassed.Ifaninitializefunctionhasbeendefined,it willbeinvokedwhenthemodeliscreated varinstance_model=newname_model2({attribute1:‘value1’,attribute2:‘value2’,…})
[70] Modelfunctionsinterface Gettingthecurrentvalueofanattributefromthemodel. model.get(attribute) Settingahashofattributes(oneormany)onthemodel. model.set(attributes,[options]) Ifanattributeissettoanon‐nullornon‐undefinedvalue,thisfunction returnstrue. model.has(attribute) Removeanattributebydeletingitfromtheinternalattributeshash.Firesa changeeventaswell. model.unset(attribute,[options]) Removeallattributesfromthemodel. Thedefaultsfunction(orhash)canbeusedtospecifythedefaultattributes forthemodelwhencreatinganinstanceofthemodel. model.defaultsormodel.defaults() Forvalidatingamodelthismethodshouldbeoverridden.Thismethodwillbe calledalwaysbeforesettingorsavingamodel.Ifitfailsitreturnsanerror, otherwiseanything. model.validate(attributes) Checkifthemodelisvalid. model.isValid() GettherelativeURLwherethemodelwouldbelocatedontheserver. model.url() SpecifyaurlRootifthemodelit’splacedoutsideofacollection. model.urlRootormodel.urlRoot() Parsethemodeldatawhenthemodelisfetchedorsaved.Fromtheserver sideinRails,itexiststheimplementationto_jsonforincludingmodel’s attributesunderanamespace. model.parse(response) Returnanewinstanceofthemodelwiththesameattributes. model.clone() Checkifthemodelhasalreadybeensavedontheserver.Itreturnsfalsein thatcase,otherwisetrue. model.isNew()
[71] Manuallytriggerthechangeevent. model.change() Checkwhetherthemodelhaschangedsincethelastchangeevent. model.hasChanged([attribute]) Retrieveahashofthemodel’sattributesthathavechanged. model.changedAttributes([attributes]) Getthepreviousvalueofachangedattribute. model.previous(attribute) Getacopyofthemodel’spreviousattributes. model.previousAttributes() Returnacopyofthemodel’sattributesforJSONstringification. model.toJSON() Resetthemodel’sstatefromtheserverbydelegatingtoBackbone.sync.Itis usefuleitherifthemodelneverhasbeenpopulatedwithdataorforensuring thatithasthelatestserverstate. model.fetch(model,response) Saveamodeltothedatabaseserver(persistencelayer),bydelegatingto Backbone.sync.Thehashattributesshouldcontainthosedesiredtochange.If themodelhasavalidatemethod,andvalidationfails,themodelwon’tbe saved.IfthemodelisNew,thesavewillbeacreate(HTTPPOST)andifit alreadyexistedwillbeanupdate(HTTPPUT). model.save([attributes],[options]) DestroysthemodelontheserverbydelegatinganHTTPDELETErequestto Backbone.sync. model.destroy([options]) Ifanyoftheattributeschangethemodelsstate,achangeeventwillbetriggered, unless{silent:true}ispassedasanoption.
[72] 6.4.3.3.4 Backbone.Collection Collectionsareorderedsetsofmodels.Itcouldbeboundchangeeventswhenany modelinthecollectionhasbeenmodified,listenforaddandremoveevents,fetchthe collectionfromtheserveranduseafullanUnderscore.jsmethodinterface. Anyeventtriggeredonamodelwithinacollectionwillalsobetriggeredonthe collectiondirectly,allowinglisteningforchangestospecificattributesinanymodelwhichthe collectioncontains. TocreateaCollection,Backbone.Collectionshouldbeextended,providing instanceproperties,aswellasoptionalclassProperties,asinthe Backbone.Modelcreation,tobeattacheddirectlytothecollection’s constructorfunction. Backbone.Collection.extend(properties,[classProperties]) Themodelclasswhichthecollectionwillcontainshouldbespecified. collection.model WhencreatingaCollection,thearrayofmodelcouldbepassedasan argument.Iftheinitializefunctionisdefined,itwillbeinvokedaswell. newCollection([models],[options]) Addamodeloranarrayofmodelstothecollection.Modelswillbeinserted regardingthedefinitionofthecomparatorfunction. collection.add(models,[options]) Addamodeloranarrayofmodelsattheendofthecollectionoratthe beginningofthecollectionrespectively. collection.push(model,[options]) or collection.unshift(model,[options]) Thesethreelattermethodsfiretheeventadd. Bydefaultthereisnocomparatorfunctiononacollection.Ifthisfunctionis definedwithinthecollection,itwillbeusedtomaintainthecollectionin sortedorder. collection.comparator Forceacollectiontore‐sortitselfwhenitisinvoked. collection.sort([options]) Removeamodeloranarrayofmodelsfromthecollection. collection.remove(models,[options]) Removeandreturnthelastorthefirstmodelofacollectionrespectively. collection.pop([options]) or collection.shift([options]) Thelatterthreemethodsfirearemoveevent.
[73] Returnanarrayofallmodelswhichmatchthepassedattributes. collection.where(attributes) SettheURLtoreferenceitslocationontheserver. collection.urlorcollection.url() Getamodelfromthecollection,specifiedeitherbyid,indexorclientid.The latterisusefulwhenthemodelhasn’tbeensavedontheserverside. collection.get(id) , collection.at(index) and collection.getByCid(cid) RawaccesstotheJavaScriptarrayofmodelsinsidethecollection. collection.models Returnanarraycontainingthehashattributesofeachmodelinthe collection. collection.toJSON() Fetchthedefaultsetofmodelsforthiscollectionfromtheserverresetting thecollection.ItdelegatestoBackbone.syncunderthecoversforcustom persistencestrategies.Italsocallsautomaticallytoparse,whichreturnsthe arrayofmodelattributestobeaddedtothecollection. collection.fetch([options]) Createanewinstanceofamodelwithinacollection. collection.create(attributes,[options]) Replaceacollectionwithanewlistofmodels. collection.reset(models,[options]) 28iterationfunctionsprovidedbyUnderscore.jssuchasforEach(each), isEmpty,etc. 6.4.3.3.5 Backbone.Router Backbone.Routerprovidesmethodsforroutingclientsingle‐pagesandconnectsthem toactionsandevents.Forbrowserswhichdon’tsupportyetHistoryAPI,theRouterhandles gracefulfallbackandtransparenttranslationtothefragmentversionoftheURL.TheHistory APIprovidespermalinkstousestandardURLspage. Duringpageload,aftertheapplicationhasalreadyfinishedcreatingallitsrouters, shouldbecalledBackbone.history.start(),orBackbone.history.start({pushState:true})toroute theinitialURL. Createacustomrouterclass.ActionswhichtriggerswhencertainURL fragmentsarematchedmustbedefined,aswellasarouteshashthatpairs routes.Hereisanexample:
c) Onc e self. u class def iata_ e defs A end Co d Inth i d) Final l 2) Req u retri e Back b e ,alltheins e u pfunction a InsertAirli n self.up Airline.c r code:"AB",i c nd elf.down irline.delet e d esnippet31: M i ssnippetis s l ythemigra t u estmodels. e vingtheinf o b onemodel s Search :c o getalist day,and contains Traveler : options. M Customer : forbooki Thismo d So,next t automat i CreditCar asthere q Order :co n models. C an Order m informat i Image6: e rtionlines w a ndthesam e n es<Active R r eate(airlin e c ao_code:"BE R e _all(:airli n M igrationfile e s hownhow t t ionwereex Thesekind s o rmationth a s .Thesemo d o ntainsthe a ofconnecti o incaseofa r travelermo d hasinforma M orethan o containsth e ngtickets,s u elisstored w t ime,ifthe u cally. d :creditcar d q uestforbu y n tainsa Cust o C ustomer,Tr a m odel.Obvi o i onisnotst o Hierarchyof o [80] w ereprinted e forthedel e R ecord::Migr a e _id:214, n R ",callsign: n e_id=>214 ) e xamplewhic h t oinsertan d x ecutedby r a s ofmodels a a ttheuser h d elscontain a ttributesfo r o nsfromon e returntripi s d els.It’ssto r tionforasi n o netraveler c e personalin u chasnam e w hentheus u serislogge d d informatio y ingtickets i o mer ,a Credi t a velers and L o usly, Credit C o red. o bjectmodels w inafilewer e e tionlines w a tion n ame:"AirBe "AIRBERLIN" ) h introducesor d deleteasi n a kedb:migra t a reactually c h asintroduc e thefollowin r makingar e e citytoano t s selected,f o r edforcreat n gletraveler , c anbeasso c formation w e ,address,p a e rislogged i d in,thefor m n.Obviousl y i ssent,this m t Card andon e egs arestor e C ard informa w hichcompos e e copiedinsi w ithinthesel rlin",alias ,country:"G e removesanai r n gleairlineb e c reatedand p e donthecli e ginformati o e questtoth e t herforasp e o rthisdaya s ingusersea r , suchasag e c iatedtoas e w henauser f a ymentmet h i nandfillst h m willbepo p y isnotstore d m odelisdes t e ormore Tr e dinthedat a t ionwithall e anOrder i detheemp t f.downfunc :"", e rmany") rline b yamigratio populated e nt‐side,as o n: e APIsinord e cifictraveli s well.Itals o rchesstatist e andtrainc a e arch f illsinthefo r hod,etc. h ebookingf o p ulated d,henceas s t royed. r aveler and L e a basecomp o theconfide n t y tion. n. erto ng o ics. a rd r m o rm. s oon e g o sing n tial
3) Resu P a a S d S f o M o t h a S c L s m s t T o t h ltconnectio riceContaine r respecialp r ndtype. chedulePoint : d ateandtim e chedule :this o rtraveling f o deOfTranspo r h ecarrierc o ndnumber ( ubLeg :forre p ontaininga S eg :represen amemean o m eaningofc o t opoverint h o ur :compos h eoriginan d Image 7 ns r :containsa r icesinclude d : containing e whenthe u modelisco m f romoneto r t :insideth o deandfligh t ( fortrainsa n p resentingt h S chedule ,a M o t stheinfor m o ftransport a o ntainingm o h istravel. e dbyoneo r d destinatio n 7 :Hierarchyof [81] llthepossib d. Price mo d itsname,ty p u sershould r m posedbyt w another. ismodelca n tnumber(f o n dpublictra h einformati o deOfTranspo r m ationtotr a a ndcancon t o rethanon e r more Leg o b n specifiedb objectmodels le Prices for d elcontains t p eofstatio n r eachthisp o w o Schedule P n befoundt h o rflights),th nsportsupp o ontotravel r t anda Pric e a velfromap t ainmoreth e SubLeg isbe b jects,repre ytheuser. whichcompo s asingleLeg, t hepriceswi orairport, c o intalongth e P oint objects h emeanoft esub‐mode o rted). fromonep o e Container m o ointtoanot h a nonesingl e causethere sentingthe w s eaTour , duesometi i thitscurre n c oordinates ejourney. andthedu r t ransportati o oftranspor t o inttoanot h o dels. herwithth e e SubLeg .Th e existsatlea w holejourn e mes n cy a nd ation o n, t ation h er, e sta e yfor
[82] 4) Usermodels. User,whichcontainstheusername,allthenecessaryattributestoencrypt thepassword,therole(normaloradminuser). ItalsoincludesreferencestoaCustomermodel,containingallthe informationforfillingautomaticallythebookingform,withoutthe CreditCardinformationandforeachtimehehaspurchasedatravelin Waymate,anOrdermodel. UserSession,modelwhichcorrespondstoaccessrestrictionfunctionality. Thesetwomodelsarecreatedforstoringsafelytheconfidential informationforuseridentification,astheuserpassword.
[83] 7.2Workflowalongtheentireprocess Theworkflowdefines: Thedataflowbetweenclient‐serverandserver‐API. Communicationbetweendifferentviewsinthesameordifferentpageviaevent triggering. PagenavigationinsteadofpagingreloadsduetoAJAXusagebyBackbone. Itwasconsideredappropriatetoincludethefollowinginformationunderthissectionaswell: Client‐sideBackboneModelobjectsandViews. Googletechnologiesemployed,givingthedetails,upsidesanddownsidesofusing them. Howvalidationworksinthebookingform
toso isat e platf o This p 1 2 Beforela meusersin e mporaryp a o rm. Thiswill b p ageinclud e 1 ) Usersw h subscrib e Image9: E 2 ) Testingu whichdo abletog o unchingWa y ordertoget a getoinfor m b ethelandi n e stwofuncti h owanttob e e toreceive e E mailsubscrip t sersandtea esn’tobtain o furtherth a 7.2.1. y mateasa p somefeed b m usersabou n gpagewhe Im a o nalities: e informed a e mailswith t t ion mcompone ausernam e a nthelandi n [84] Landin g p ublicapplic a b ackandim p u twhatWay m nusersacc e a ge8:Landing p a boutthest a t hisinforma t ntscanlogi e andpassw o n gpage,bec a g page a tion,apriv a p rovesome a m atewillpr e e sstowww. w p age a teandupd a t ion. nforaccess i o rdprovide d a usetherei s a teversion, w a spects,will b e sentastra v w aymate.de. a tesabout W ngtheappli c bythecom p s nopossibili w hichisres t belaunched v elsolution . W aymateca n cation.Aus e panywon’t b tyyettosig n ricted .This e r b e n up.
ascri alrea still m byo n Oncethe ticalorimp o dyawareth a m issingorn e Hence,t h n e,arenota c teamhasg o o rtantwillb e a tdesigniss e edtobeim p h efollowing c cessibleye t Image10:Lo g o tfeedback f e implemen t ues,interfa c p roved. pages,whic h t tothepubl [85] g inwindowin f romthetes t edbydevel o c einteractio n h belongto t ic. landingpage. tingusers,t h o pers.Neve r n andadditi o t heapplicati h eimprove m r theless,the o nalfunctio n o nandwill b m entsconsi d entiretea m n alityfeatur e b eexplaine d d ered m is e sare one
com p 1 corr e com p resp o com p sugg e dele t mea n 37Go o Onthes e p osedbytw o Mapview , preserve d reloadal o connecti o Searchv fromaci t Therear e 1 ) Searchf Inorder t e spondingin p p letename h Itcanbe o nseandac c p letionpow e Itisalibr e stionslist, w t ingcharact e n sthatanas o glePlacesa u e archpagei s o differentB , wherethe o d alongthe e o ngtheapp l o nsinadvan iew,where t t ytoanothe e 3different i ororigina n t ofacilitate t p utfields,a h eissearchi n Imag e saidthatis t c uracydispla e rinGoogle arywhichh a w hichchang e e rs.Eachtim ynchronous u to‐complete: 7.2.2 . s wherethe t ackbonevie w o riginandd e e ntireproce s icationproc cedstages. t heuserset rforspecifi c i atedsteps w n ddestinat i t hisprocess, listofsugge s n g. e 11:Searchpa Google hebesttec h yingsugges t mapswebsi t a ndlesasync e seachtim e e thesugge s requesthas https://deve [86] .Searc h t ravelerwill w swhichu p e stination m s sundestro y ess.Thema p alltheattri b c daysanda w ithintheS e ioncitieso whentheu s stionsshow s a ge.GooglePla Placesa u h nologyfou n t ionsforciti e t eembedde d c hronousre q e theinputfi s tionslistch a beensent, r lopers.googl e h page startplanni n p dateeacho t m arkersared y ed.Thisisp p willshow m b utesrequir e determined e archview: raddress. s ertypesso m s up,preven t cesauto‐com p u to‐compl n dsofarfor t e sandaddr e d inthisapp q ueststoGo o eldcontent c a nges,duet h r eceived,pa r e .com/places / n ghisjourn e t herviaeve n isplayed.Th i ossibledue t m oreaccura t e dforsearch numberof t m ethingwit h t ingtheuse r letion. ete 37 t hispurpose e ss.It’sactu a lication. o glePlaces A c hanges,eit h h einputfiel d r sedanddis p / documentati o e y.Thispage n ttriggering isviewwill b t hereisno p t einformati o h ingconnect i t ravelers. h inthe r totypethe e ,givenitsfa a llytheauto ‐ A PIanddispl hertypingo d haschang e p layed. o n/autocom p is . b e p age o nfor i ons st ‐ aysa r e d, p lete
[87] Oncetheuserselectsanoptioninthesuggestions’list,anotherrequestissentto GooglePlacesAPI.Thistimetheresponseisanobjectcontainingallthedetailsabouttheplace selectedinJSONformat,suchascoordinates,name,place’stype,etc. Intheend,themostimportantattributesarethecoordinates,whichareusedtoget theclosestairportsandtrainsstationswhichwillbemadetherequestinordertoget connections. Geocoder38 Whentheuserpressesthesearchbuttonandhasn’tselectedanoptioninthelist,but hasintroducedthenameofacity,eitherfororiginordestination,whatdoesithappen? ArequesttotheGeocoderserviceisdoneinordertoobtainthecoordinatesandmore detailsassociatedtothatplace.ThisserviceisalsosupportedbyGoogleanditalsoprovides theGeocoderreversefunctionality,whichpassingthecoordinatesintherequest,itreturnsin theresponsetheplacedetails,suchasname,address,etc. Thisserviceguaranteesalwaystoobtainthecoordinatesfromthenameoftheplace introducedintheinputfield. Comparingauto‐completionalternatives Thefirsttechnologyemployedforauto‐completionwasGeocoderauto‐complete, whichisnotthesameservicethanGeocoder.ThesetechnologiesarepoweredbyGoogle, nevertheless,thelatterpresentedsomeimportantlackswhicharesolvedusingGooglePlaces auto‐complete: Thepriorityofshowingaddresssuggestionsprevailsovercities.Travelerswill searchmainlyforcitiesinsteadofaddress,thereforethiswasaproblemfor Waymate. Whenafewcharacterswereintroduced,thesuggestionlisthardlydisplaysa fewresultsandwithoutanyaccuracy.Aslesscharacterstheuserhasto introduce,thebestexperiencewillenjoy,duetothefastandeasyprocess. Whenacityissearchedusestoappearinthesuggestions’listalmostafter typingtheentirename. TheonlyadvantagewhichGeocoderauto‐completepresentedwasitsbetter performanceandaccuracy,afterhavingintroducedmorethan5characters,fordisplaying addressinthesuggestions’list. 38Geocoder:https://developers.google.com/maps/documentation/javascript/geocoding
[88] Googlemaps39 Themapplaysanimportantrolealongtheprocessintheapplication.Thereasonis becausewhentravelingthereexisttwomaindimensions,spaceandtime. Includingthemap,andshowingtheoriginanddestinationafterbeingselected,gives totheuseravisualfeedback,representingthespacedimension. Atthisstage,theusercanplayaroundwiththemap,selectinghisoriginordestination byclickingoverthemapormodifyingitbydraggingthemarkersaftertheyhaveshownup.For bothactions,themarkerobtainsthecoordinateswherethemarkerisplacedinthemap. Hence,havingthecoordinates,arequesttoreverseGeocoderisdone,gettingthedetailsof theplaceandupdatingitscorrespondinginputfield,eitherfororiginordestination,withthe nameoraddressoftheplace. HowtouseGoogleservices Forusingtheservicesexplainedpreviously,itwillberequiredtoaddbetweenthe <head></head>htmltagsthefollowingline: <scripttype="text/javascript" src="//maps.google.com/maps/api/js?libraries=places,geometry&rankby=prominence"></script> ThesourcewithoutanyparametersgivesaccesstoGeocoderandGooglemaps services.Moreservicesareavailable,butnotusedinthisapplication. TheparameterlibrarieswiththevalueplacesincludesGooglePlacesauto‐completeand GooglePlacesservices.Inaddition,withthevaluegeometryaddsalibrarytocalculatethe distancebetweentwopoints,havingintoaccountthattheEarthisasphere. Theparameterrankby=prominencemeanstogetsuggestionsbyimportancewhenusingGoogle Placesauto‐complete. Googleservicesdownsides WaymatefunctionalitydependsonGoogleservices.Functionalitieswhicharecrucial alongtheprocessintheapplication,asgettingcoordinates,relyontheseservices.Ifoneday, Googleservicesarenotavailable,theapplicationwon’twork. Additionally,forbusinessapplicationsit’srequiredtogetabusinessaccount.Before gettingthisaccount,thepriceofeachrequestandtheserviceswhichwillbeaccessiblemust benegotiatedandspecifiedinacontract. Theretwoimportantdownsides,butinthemarket,servicesaspowerfulastheones whichGoogleprovidesdon’texist.Anexceptioncouldbedoneregardingmapsservices, mentioningalternativessuchasNokiamaps,OpenStreetMaps,etc.ButGoogleprovides additionalfeaturestothemapswhicheventuallycouldbeinterestingtoadd. 39GoogleMapsAPI:https://developers.google.com/maps/documentation/javascript/reference
2 T outb o he’ll h inbo u I n acal e date / whic h bea d 40Da t 2 ) Selecto u T heseconds t o unddate, a h avetosele c u nddateis n n steadofha e ndarwitha / s.Thecale n It’sn Inbo u Onc e selec case, the n Whe n outb o cale n Asin box b Thecale n h offersalo t d dedwithin < <%=javas c t epickerAPI: h u tbounda n t ep,afterh a a ndifthetra c ttheinbou n otselected vingtwose p customized n dar’sfuncti otallowedt o u nddatesel e e theoutbou ted,unless t theoutbou n n extclickifd n theboxco o undorinb o n dar. bounddate b elowtheca n darcompo n t ofoptions t < head></head > c ript_includ e h ttp://jquery u n dinbound a vingbeens e velerwants n ddate.Int i twillbeao Image1 2 p aratedcale n functionalit o nalityisas o pickaday e ctionisopt ndisselect e t hedaysele c n dwillbere e sired. ntainingthe o undwillbe isoptional, c lendar. n entisactua t obecusto m > inthetem p e _tag'jque r u i.com/demo s [89] date. e lectedorigi tocomeba c hiscasethe newaytrip. 2 :Searchpage. n darsforou t t ywhichma k follows: inthepast. t ional. e d,withthe n c tedisbefor e selectedan d dateforma t chosenafte r c ouldbere m llyafamous m ized.Toint e p latewhere r y.tools.min. s /datepicker/ nanddestin c kfromthe s travelwillh a Calendar. t boundand k eseasyand n extclickth e e thecurren d theinbou n t tedbelowt r thenextcli m ovedbycli c jQueryplug e grateitint h it’sused: js'%> ation,istos s amedestin a a veareturn inbound,W a fastthewa y e inboundd a t outbound c dwillhave t hecalendar ckoversom c kingtheclo s in,namedD h eapplicati o s electthe a tionandori tripaswell. a ymatepres y topickspe a tewillbe chosen.Int h t obeselect e willindicat e edayinthe s eiconwith i D atePicker40, o nthislines gin, If ents cify h is e din e if i nits h ould
allth can b 1 2 Afterthe edetailsres b edifferenti a 1 ) Map . H Inthisst a TheCon n whichisl andallt h map,sol v T clicksov e 1) N 2) A 3) D 4) S 5) C n Allthese Fororigi n Fortheo 2 ) Navigat i userclicks o pectingthe c a ted: H ere’sthep o a ge,mapsol n ectionsvi e istenedbyt h estopovers v ingthespa c hetimerep r e ramarker, N ameofthe A rrivaltime a D epartureti m S topovernu m C arrierinfor m n umberfort r information n marker’sin newhichco r i onbar whi c 7.2.4 . o veraconne c onnections Ima g o intalongth e v estimean d e wtriggersa n h eMapview , associated t c erepresent r esentationi displaying: trainstatio n a nddate. m eanddate . m ber. m ation,airli n r ains. willbeatta c fo‐window w r respondst o c hisalready [96] . Detail s ction,then e selected.In g e24:Details p e processw h d space,alli n neventwit h , wherethe d t otheselect ation. i ssolveddis p n orairport. . n eandflight c hedtoeac h w illbedispl a o thedestin a explained. s page e xtstepint h thedetails t p age. h erethema p n one. h theconnec t d etailsared edconnecti o p layinganin numberfor h markerwh i a yed1),3)a n a tiononly1) , h eprocessw t hereareaf e p acquiresm t ionselecte d isplayed.Or i o nwillbedi s fo‐window w flightsandt y i chrepresen n d5). 2)and4). w illbetodis p e wsections m oreimport a d informatio igin,destina t s playedove r w hentheus e ypeoftrain tsastopov e p lay w hich nce. n t ion r the e r and e r.
3 4 3 ) Gener a B stopover s 4 ) Details . I t sub‐view Con n rega r over v Price one w Image2 7 Therele v a lrepresen t B ardisplaye d s . Image25 : t ’smade‐up s: n ectiondeta i r dingtime,c a v iewofthe e Ima g switching.I w hichprefer 7 :Detailspage . v antinforma Ima g t ationofa c asinthere s : Detailspage. G byDetailsvi e i lsexpande d a rrierandst e ntireconne c g e26:Details p f thereexist s s. Priceswitchin t ionforthe g e28:Details p [97] c onnection s ultsframe, Generalrepre s ewandaC o d .Whenthe ationsorair c tionwithit s p age.Connecti o smorethan n g priceisexpl a p age.Conditio n . butexpand e s entationofa c nnectionm o buttoni s portsaredi s s sub‐conne c o ndetailsexp a onekindof a inedinthis n sforatypeof e d,date,du r c onnection o del.Itinclu d s clicked,all t s playedgivin c tions. a nded price,theu s section: price r ationand d esthefoll o t hedetails n ganother s ercansele c wing c tthe
T whic h 4 5 Whenth i thesam e pricecha Itinvolv e 1 2 3 4 T heconnecti o h willbere‐ u 4 ) Travele r T wrong.It detailsp a I m 5 ) Goton e Sele c theo I n c u c Got o i spageislo a e thefirstti m ngessincet h e sthesestep 1 ) Areques t oftheco n 2 ) Oncethi BahnAPI 3 ) Thecorr e thenew p 4 ) Fromthe displaye d o ndetailse x u sedinadva r s’informa t heusersho u iscompose d a ge. m age29:Detai e xtstep .Th e c tinboundc o utboundtra n thiscase, t c ompatiblec u serselects o c ombination , o thebookin a dedaprice v m ethatthet y h euserhas e s: t fromthecl n nectionan d s informatio . e spondingA P p riceincase server‐side d . x pansionan d n cedsteps. t ion . u ldbeawar e d bytheTra v l spage.Travel e e rearetwo o o nnectionif velbypress i heuserwill o nnections r o newillber e , hewillpre s gformforb [98] validationi s y peofprice e nteredthe ienttothes d thepricet o nisonthec P Isendsbac ithaschan g thisinform a d priceswitc e oftraveler s v elers’colle c e rsprofileset. o ptions: returntrip e i ngthisbutt o bearesults r egardingth e e directedto s sthebutto n b uyingtheti c s triggeredf o isswitched. firsttimeto erver‐side w o validate. lient‐side,it ‘ k totheser v g ed. a tionissent t hingcompo s s settingate c tionwitha s e xistsandth o n. pageforth e e onechose n thedetails p n forgoingt o c ketsbyclic k o rtheprice p It’sperform theresults p w iththerele v ‘ ssenttoYp s v er‐sidethe v t otheclient ‐ s esConnect i achstagein s pecifictem p e connectio n e inboundtri n foroutbou p age.Ifheis o thebookin g k ingthisoth e p reselected a edincaset h p age. v antinform a silonorDeu v alidationw i ‐ sideand ionInfovie w casethey’r e p lateforth e n selected w pwith u nd.Onceth interestedi g form. e rbutton. a nd h e a tion stche i th w , e w asfor e nthe
ticke t Atthisst a t sboughta n 1) M 2) N 3) D i n t h c p t h Image a getheuser n dbesidest h M ap . N avigation t D etailsfor c The d n theDetails , It’si m h ewholepr o heckagaint h rice,ifitexi s Trav e h emunless a 30:Bookingfo 7.2.5. willfillthe f h epayment m t ab. c onnection s d etailsforea , namedCo n m portantto k o cess.Reach h edetailso f s ts,heisgoi n e lerssetting a a newsearc h rm.Traveler p [99] Bookin g f ormwithit s m ethod.Dif s selected. chconnecti o n nectionIn f k eepinform e h edthispoin t f theconnec t n gtopayfo r a redisplaye d h isdoneor t p rofilesetand d g form s personald a f erentsecti o o ncorrespo n f oview. e dthetrave t ,thetravel e t ionschose n r . d aswell,b u t heyaremo d d etailsviewfo r a taforassoc i o nscouldbe n dstothes u l erabouthi s e rprobably w orevench a tthereisno d ifiedfromt r selectedcon n iatinghimt h distinguish e u b‐viewemp s choicesalo w ouldliket o a ngethetyp e o choicetor e t heresultsp a n ections h e e d. loyed ng o e of e set a ge.
4) S R s a a 5) C i n r t b W e f o i n S eatreserva t Itco m R eservatio n This s elected.Th e a ndthesele c a reincluded Ima g C ustomerp e Inth i n troducehi s It’sc o epresentth e Cust o ickets.Ticke t b elongs.Inc a W aymateca n Thisi e nterstheb o o llowingti m n formation a t ion. m posedbyB o n associated s ectionwill o e travelerwil c thisseat.A inthisarea, g e31:Booking Image32:B o e rsonalda t i ssectionbe personald a o mposedby e dataassoc i o merperson a t swillbeas s a sethatso m n obtainhis p n formation w o okingform t es,theuser a ndnotfillt h [100] o okingRese totheview. o nlyappear w lhavetoac t lltheterms aswellast h g form.Seatre s ookingform. S t aandadd r e ginsthebo o a ta. BookingCu s i ated. aldatawilli d s ociatedtot m eerrorocc u p ersonalda t w illremaini t obuyanot h mustbelog h issectiona g rvationvie w hentraini s t ivatereserv andconditi o h eadditional s ervationcond i S eatselection r ess. o kingform w s tomerview d entifythe u heperson w u rswhenth e t a,contacth ntheinput f h erticket.O b gedinifhe w g ain. wanditsm o s includedin a tionbyen a o nsregardin g pricewhich tions w heretheus e andthemo d u serwhowil w hoseperso n paymentis i mandsolv e f ieldsnextti m b viously,th e w antstosto r o del theconnec t a blingtheb u g seatreser v h willbecha r e rhasto d elCustome lpurchaset h n alinformati performed, e theproble m m etheuser e firstandth re/keepthis t ions u tton v ation r ged. rto h e on m . e
6) C T T O b u 7) T T t r Image3 3 C reditcard i T hissectioni T hepurchas e V M A D J C I m O nlineidenti f b ecauseDeu s u serwhowil l C D I d M I T ravelers’p hisinformat r avelisfrom 3 :Bookingfor m i nformatio n s integrated e willbefulfi V isa M asterCard A mericanEx p D inersClub C B m age34:Booki n f icationsect s tcheBahn r l purchaset h C reditcard. D eustcheBa h d number. M aestrocar d mage35:Boo k ersonalinf o ionwillonly Germanyt o [101] m .Customerp e n andonli n byBooking lledbycredi p ress n gform.Credi t ionwillsho w r equiresit.T h etickets.Id h ncard. d . k ingform.Onli n o rmation. y berequire d o anotherco e rsonaldataa n n eidentific a CreditCar d tcardpaym t cardinforma t w uponlyw h hisidentific a entification n eidentificati o d alwaysfor f untry. daddress a tion. d viewandC r e nt.Thetyp e ion h entraintic k a tionmustb canbefulfill o n f lightsandf o r editCard m essupporte d k etsareinv o ewithdata o l edby: o rtrainswh e m odel d are: lved, o fthe e nthe
After user w possi possi pass e asin g whic h erro r valid a insta n E m 8) T T D r fillingallth e w illpressth i Thereis s bletoguara bletomake Therefor e e dthevalid a g leinputfiel h notpasses r .Validation a tionit’sdo n n taneousfe e achtraveler m odel. Image T ermsand c T helinesspe D eustcheBa h I m e inputfield s i sbutton s tillanimpo r nteethatth surethatal l e ,whenthe a tion,aswell ddoesn’tp a thevalidati o isdoneinlin n eforthats i e dback. isaBookin g 36:Bookingf o c onditions. cifiedforthi h n,hasprov i m age37:Book i V s andselect t t r tantproces s e userhasfi l l theinputfi e userclickst h ascheckbo x a ssthevalid a o n,apopu p easwell,w h i ngleinputfi [102] g Traveler v o rm.Travelers’ ssectionwi l i dedtheco n ingform.Ter m V alidatio t hecorresp o t opurchase s toexplain, lledallthei n e ldsarefille h ebuttonfo x eswhichm a tion,thefo r p windowwi l h ichmeans w i eldinthat m v iewandits c personalinfo r l lvarydepe n n nectionsel e m sandconditio n o ndingoptio thetickets. butnotvisi b n putfieldsp r dinthepro p rbuyingtic k ustbechec k r mwon’tbe lappearab o w hentheus e m oment,pro c orrespondi n mation n dingonwhi e cted. ns n sinthedr o b letotheus e r operly.Ho w p erformat. k ets,allthei n k edbeforet h sent.Forea o vetheminf o e rleavesan v idingtoth e n gTravele r chAPI,Ypsil o pdownlist s e r.It’snot w ever,it’s n putfields m h eformiss e chinputfiel f ormingabo u inputfield, e user r onor s ,the m ust e nt.If d u tthe
Cust o com p from Validatio n Inputfiel valuewi t statically Creditca ownreg u whichis a Individu a thedate introduc e Expiratio Birthday introduc e Oncevali omer,Cre d p oseaconta Further m thebookin g Storedi n havedo n beassoc referenc Afterwa r Bahnor b server‐si I f aboutw h willredi r I n types: dswithincu t hapredefin .Thesame v rdnumberi n u larexpressi o a checksum f a linputfield s includesad a e d.i.e.30/0 2 ndateinput datesfora d e dmustbei n dationsucc e d itCard,coll iningobject m ore,whent h g form,isse n n thedataba s n e.Whenth e iatedanda c etotheuse r r dsrequesti b othAPIs.T h de,parseda f anerroroc c h athappen e r ecttotheti c mage38:Pop‐ stomerdata edregulare v alidationis d n putfieldi m o ntomatch f ormulatov s whichcom p a yinputfiel d 2 /2013woul fieldsarev a d eterminea g n therange o Tickets p e ssforallth e ectionofTr namedasO r h eOrderob j n ttotheser v s einordert o e ticketisb o cessibletot r . nXMLform a h eresponse ndsenttot h c urs,thepa y e d.Otherwis e c ketspage. [103] uperrorswhe n ‐addressse c e xpression.T d onefortra v m pliesmore c andfurther v alidateiden t poseadate d ,thedaym dn’tbevali d a lidateddyn a g earealsov a o fspecified a p urchas e e inputfield s avelersan d r der. b jectiscomp v er‐sideand : okeeptrac k o ught,ifthe heuser.Ot h a tisbuiltto followsthe h eclient‐sid e y mentwillb e e ,iftheboo n validationfa i c tionareval i hus,canbe s v elers’nam e c omplexity. E m ore,itmu s t ificationnu m arevalidate d ustbevalid d . a micallycon a lidateddyn a getopass t e reques t s theformc a d Connecti o letedwitht h : k aboutallth userwaslo g h erwise,itw i senditeith e sameflowa e . e cancelled a kingandpa y ls datedbym a s aidthatar e e andsurna m E achtypeof s tpasstheL u m bers. d withareg u d epending o sideringthe amically.H e t hevalidatio t a nbesent.R o nsobjectm h einformati o epurchases gedin,this O i llbestore w e rtotheYps i salways,re c a ndtheuser y mentsucce s a tchingthei r e validated m e. creditcard h u hnalgorith u larexpressi o nthemont h currentdat e e nce,theag e n. R eservatio n m odelswill o nthatcom thattheus e O rderobjec t w ithoutany i lon,Deustc h c eivedonth e willbenoti f s s,theappli c r h asits m, on.If h e . e n , es e rs t will h e e f ied c ation
t h t r M T a e i c Iftheus e heconnecti o rainsandfli g M ap,Naviga t T heonlydist i a lreadyboug Image Allticket s e xception.D e c on a e rhasreach e o nsselected g htticketsi n t ionTaband i nctionwill b httheticke t 39:Tickets.Tr a s willbesen t e ustcheBah n a ndbeingre Image 7. 2 e dthispoint havebeen b volved.Allt i Detailsvi e b ethattheu t s. a velersprefer e t totheema n ticketswill directedto a 40:Tickets.Ti c [104] 2 .6.Tic k alongthea p b ought.No m icketsareb o e wswillrem serwon’tb e e ncessetandd iladdresss p beavailabl e a nURLwhe r c ketspurchase k ets p plication,it m atterhow m o ughtinasi n ainonthet o e abletoswi t etailsviewfor p ecifiedinth e aswellfro m r easingleti c linksandinfo r meansthat m anywere o n gleprocess . o p,asinthe t chpricesb e purchasecon n e bookingf o m thispage b c ketisinPD F r mation alltheticke t o riftherew e . bookingfor m e causeheh a n ections o rmwithout b yclickingi n F format. t sfor e re m . a s n this
T Boo k proc e up. I n provi Book carry T heuserwill k ing.com.H e e ss.Iftheus e n Waymate, dedbyBoo k k ing.comwill ingoutaho t beabletob e willhavet h e rdoesn’ts e thehotels p k ing.com.It h knowthati t t elbookingi 7.2.7. H ookahotel d efreedomt e lectthecor p ageit’sane h asanidass t ’sbeendon sincludedi n Imag e [105] H otels b d uringhisst obookitin t responding t mbeddedif r s ociatedto W n ethrought h n theiframe . e 41:Hotelsb o b ooking ayinthecit y t hemomen t t abforhote l r amedefine d W aymate,so h isapplicati o . o oking. y whichspec whichhed e s,thispage w d intheBoo k ifauserwill o n.Allthefu c ifiesin e cidesalong willnevers h k ingviewa n l bookahot e nctionalityf o the h ow n d e l, o r