Introduction To Rails Rails Principles Lecture 18: Ruby On Rails Inside .

Transcription

OutlineIntroduction to Rails Rails Principles Inside Rails Hello World Rails with Ajax Other Framework Lecture 18: Ruby on RailsWendy LiuCSC309F – Fall 200712MVCIntroduction to Rails“Agile Web Development with Rails”2nd Ed, D. Thomas et al.341

Rails A Typical Rails ApplicationIncoming requests are first sent to a router,which determines where to send and how toparse the request A particular method, or action, is called insome controller The action might look at data in the request,interact with the model, or cause other actionsto be invoked The action prepares information for the view,which renders the output to the userRails enforces a structure for the application MVCarchitecture Models, views, and controllers are developed asseparate chunks of functionality and knittedtogether by Rails Little external configuration metadata is needed Conventionover configuration philosophy56Rails and MVCWhy Rails MVC seems to do the trick, why do we needRails? Railshandles all of the low-level housekeepingfor you—all those messy details that take so longto handle by yourself—and lets you concentrateon your application’s core functionality Controller: storeAction: add to cartModel: (shopping cart) params[:id] 123782

Painstaking Mappings Mappings we have seen and used Deployment descriptors Persistence data binding Transport data binding Rails Principles JDBC data mappings (Class to table)WSDL and JAX-B data binding (Class/Field to XMLelement/attribute)MVC mapping Servlet mappings (URL to Servlet class)Model to View to Controller (usually hard coded)All stored and performed differently Learning curve, maintenance cost910Top Two Principles Convention over configuration Noexplicit mapping needed Suchas deployment descriptorsInside Rails Usenaming conventions to automaticallyperform the mapping E.g.Store controller vs. store view Tofight back the proliferation of configurationsseen in J2EE DRY (Don’t Repeat Yourself) Informationplaceis located in a single, unambiguous11123

Components of Rails OO vs RDBActive Record Model Relationaldatabases are designed aroundmathematical set theoryAction Pack ViewApplications are often Object Oriented, theyalso keep information in a relational databaseand Controller Allabout sets of values Objects are all about data and operationsOperations that are easy to express inrelational terms are sometimes difficult tocode in an OO system, and vice versa1314Object-Relational Mapping (ORM) ORM (cont’d)ORM libraries map database tables to classes Ifa database has a table called orders, we willhave a corresponding class named Order Rows in this table correspond to objects(instances) of the classRails (model) classes provide a set of classlevel methods that perform table-leveloperations Forexample, we might need to find the orderwith a particular id Aparticular order is represented as an object of classOrder Thisis implemented as a class method that returnsthe corresponding Order object Withinthat object, attributes are used to get andset the individual columns OurOrder object has methods to get and set theamount, the sales tax, and so on15164

Active RecordExample: Active RecordModel support in Rails The ORM layer supplied with Rails SQLCREATE TABLE people (id INT(11) NOT NULL auto increment,name VARCHAR(100),PRIMARY KEY (id)) tablesmap to classes, rows to objects, andcolumns to object attributes Active Recordclass Person ActiveRecord::Base; endPerson.create(:name "Lucas Carlson")lucas Person.find by name("Lucas Carlson")lucas.name "John Doe"lucas.save1718Action Pack Action Pack: View SupportBundles both views and controllers Theview and controller parts of MVC are prettyintimate controller supplies data to the view The controller receives events from the pagesgenerated by the viewsCreating either all or part of a page to be displayedin a browserDynamic content is generated by templates rhtml rxml The Rails provides a clear separation for controland presentation logic Embeds snippets of Ruby code within the view’s HTMLLets you construct XML documents using Ruby codeThe structure of the generated XML will automatically followthat of the coderjsAllows you to create JavaScript fragments on the server whichare to be executed on the browser Great for creating dynamic Ajax interfaces 19205

Example: Rails ViewAction Pack: Controller h1 Hello world! /h1 p The count is % @some number % /p Coordinates the interaction between the user, theviews, and the model Rails handles most of this interaction behind the scenes ul % for i in 0.@some number do % li % i % /li % end % /ul You only need to add the application-level functionalityOther responsibilities Routing external requests to internal actionsManaging caching Managing helper modules Give applications orders-of-magnitude performance boostsExtend the capabilities of the view templates without bulking uptheir codeManaging sessions Giving users the impression of ongoing interaction with theapplications2122Example: Rails ControllerHow to Interpret URLs in Railsclass PersonController ApplicationControllerdef index# local to the method ONLYsome number 5endExample:http://localhost:3000/person/count/123 persontranslates to the PersonController class count translates to the count method 123 translates to the value of params[:id]def count# local to the method AND the view@some number 5endend23246

That's Not All ActionWebServices XML views Create SOAP and XML-RPC web services in minutesCreate RSS in secondsEasy, well integrated unit testingAutomated documentation generationAutomated benchmarking and integrated loggingInteractive debuggerEasy custom routesPlug-ins2526Create Application: demoHello WorldBuild a Rails App:Illustrating Convention over Configuration27287

Directory Listing: demoStarts Web Server Starts a stand-alone web server that can runour newly created Rails application underWEBrick (default)2930Create New Controller: SayNewly Created Rails Application31328

Inside Say ControllerAdd Method to Say Controller3334Rails Routes to Controllers and ActionsURLs: Mapped to Controllers and Actions35369

Go to the Link Create a Template (View)http://localhost:3000/say/helloBy default, Rails looks for templates in a filewith the same name as the action it’s handling We need to create a file called hello.rhtml inthe directory app/views/say/ 3738Standard Locations for Controllers andViewsHello!394010

Adding Dynamic ContentHello and Goodbye!4142Story So Far1.The user navigates to our application 2.3.In our case, we do that using a local URL such ashttp://localhost:3000/say/hellosearches the directory app/views for asubdirectory with the same name as thecontroller (say) and in that subdirectory for afile named after the action (hello.rhtml)The say part is taken to be the name of a controller, soRails creates a new instance of the Ruby classSayController (which it finds inapp/controllers/say controller.rb)4.The next part of the URL path, hello, identifies anaction Rails looks for a template to display the result ItRails analyzes the URL 3.Story So Far (cont’d)Rails invokes a method of that name in the controllerThis action method creates a new Time object holdingthe current time and tucks it away in the @time instancevariable435.Rails processes this template through ERb(Embedded Ruby), executing any embeddedRuby and substituting in values set up by thecontrollerThe result is returned to the browser, andRails finishes processing this request4411

RJS Template Idea: Your XHR calls can return JavaScript toexecute in the browser Rails with Ajax Solving problems that otherwise require a great deal ofcomplex JavaScript on the clientA RJS template is a file in app/views/ with an .rjsextensionWhen a request comes in from XHR, the dispatcherwill preferentially look for an .rjs template The template is parsed, JavaScript is generated andreturned to the browser, where it is finally executed4546Related Framework Django for Python Features: MVC-basedOther Framework Object-relationalmapping DRY (Don’t Repeat Yourself) Principle Easethe creation of complex, DB-driven webdevelopment Emphasize reusability and pluggability Automateas much as possible Supportfor rapid development http://www.djangoproject.com/474812

Rails looks for a template to display the result It searches the directory app/views for a subdirectory with the same name as the controller (say) and in that subdirectory for a file named after the action (hello.rhtml) 4. Rails processes this template through ERb (Embedded Ruby), executing any embedded Ruby and substituting in values set up by the