Rails 101 - Elite.polito.it

Transcription

Introduction and first applicationLuigi De RussisRails 101

2Rails 101About Rails 17/03/2015

Ruby on Rails3 Framework for making dynamic web applications createdin 2003 Open Source (MIT License) for the Ruby programming language based on the MVC (Model-View-Controller) pattern with a built-in support for Ajax (jQuery) Website: http://rubyonrails.orgRails 10117/03/2015

The Rails Way4 Convention over Configuration (CoC) principle usenaming conventions to automatically perform themapping example:every model is automatically included in thecontrollers lesscode, but can be confusing to beginners canbe hard to look under the hood makeassumptions about what you want to do and howyou are going to do it ratherthan requiring you to specify every little thing throughendless configuration filesRails 10117/03/2015

The Rails Way5 Don’t Repeat Yourself (DRY) principle information is located in a single, unambiguous placeObject-Relational Mapping (ORM) mapdatabase tables to classes model classes have a set of class-level methods thatperform table-level operations REST (REpresentational State Transfer) useresource identifiers such as URLs to represent“resources”Rails 10117/03/2015

REST6 Handle resourcesa document or image a service a collection of other resources A resource is the source of specific informationMapping between resources and URIsOperation on a resource is done by means of HTTPmethods GET, POST, PUT, DELETERails 10117/03/2015

REST: main resources7 Collection resource Represent a set of itemshttp://mysite.com/users http://mysite.com/students Use plural, concrete nounsElement (item) resource Represent a single item and its propertieshttp://mysite.com/users/1 http://mysite.com/students/s123456 Inside a collection, typically Use numbers or singular, concrete nouns Rails 10117/03/2015

REST: HTTP methods8 GET retrieve the representation of the resource POST create a new resource apply on a collection, typicallyPUT update an existing resource collection: the list of itemselement: the item’s propertiesapply on a elementDELETE delete an existing resource Rails 101apply on a element17/03/2015

Structure of a Rails applications9app/Core application (app) code, including models, views, controllers, andhelpersapp/assets/Applications assets such as cascading style sheets (CSS), JavaScriptfiles, and imagesconfig/Application configurationdb/Database filesdoc/Documentation for the applicationlib/Library moduleslog/Application log filespublic/Data accessible to the public (e.g., web browsers), such as error pagesscript/railsA script for generating code, opening console sessions, or starting alocal servervendor/Third-party code such as plugins and gemsRails 10117/03/2015

Structure of a Rails applications10README.rdocA brief description of the applicationRakefileUtility tasks available via the rake commandGemfileGem requirements for this appGemfile.lockA list of gems used to ensure that all copies of the app use the samegem versionsconfig.ruA configuration file for Rack middleware.gitignorePatterns for files that should be ignored by GitRails 10117/03/2015

11Rails 101You first Rails app17/03/2015

Create the application12 Open RubyMineCreate a new project Name:Lab1 Type: Rails application In the next window, select RailsVersion: 3.2.x Preconfigure for selected database: sqlite3 Skip Test::Unit files Wait Rails 10117/03/2015

Be aware 13 RubyMine may ask you for installing missing gems accept!On Linux, the error “Could not find a JavaScript runtime”may ariseto fix it, open the “Gemfile” and uncomment the“therubyracer” gem from the Tools menu in RubyMine, select Bundler and Install Due to some limitation to the Poli network, on desktopcomputers, you may encounter some errorsto fix them, open the “Gemfile” and replace “https://.”with “http://.” in the first line from the Tools menu in RubyMine, select Bundler and Install Rails 10117/03/2015

Bundler and the Gemfile14 Manage the application’s gems dependenciesAutomatically run during the Rails app creationRead the Gemfile to install the correct gemsInstall the declared version of the gemInstall the latest version of the gemInstall a version of the gem lower than 3.3Install a version of the gem greater than 1.0.3Rails 10117/03/2015

See the result15 Start the web server (WEBrick) press Run Open a browser http://localhost:3000/Rails 10117/03/2015

17Exercises 2 and 3Let’s do them!Rails 10117/03/2015

18Rails 101Final thought 17/03/2015

ERb (Embedded Ruby)19 View files in a Rails application looks like an HTML5document but with a supplementary .erb extensionERb is a templating library that lets you embedRuby into your HTMLTwo tag patterns to learn forevaluating Ruby code % some code % outputevaluated Ruby code % some code % Rails 10117/03/2015

How the final app works 20 The user navigates to our application in our case, we do that using a local URL such ashttp://localhost:3000/greeter/hello Rails analyzes the URL and looks in the applicationroutes (in config/routes.rb) the greeter part is taken to be the name of a controller, soRails creates a new instance of the classGreeterController (which it finds inapp/controllers/greeter controller.rb)The next part of the URL, hello, identifies an action Rails invokes a method of that name in the controllerRails 10117/03/2015

How the final app works 21 Rails looks for a template to display the result itsearches the directory app/views for a subdirectorywith the same name as the controller (greeter) and inthat subdirectory for a file named after the action(hello.html.erb) Rails processes this template through ERb, executingany embedded Ruby and substituting in values setup by the controllerThe result is returned to the browser, and Railsfinishes processing this requestRails 10117/03/2015

Some useful resources 22 Code School - Rails for Zombies http://railsforzombies.org Ruby on Rails: documentation http://rubyonrails.org/documentation Ruby on Rails Screencasts - RailsCasts http://railscasts.com Learn Web Development with the Ruby on RailsTutorial http://rails-3-2.railstutorial.org/bookRails 10117/03/2015

License23 This work is licensed under the Creative Commons “AttributionNonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License.You are free: Under the following conditions: to Share - to copy, distribute and transmit the workto Remix - to adapt the workAttribution - You must attribute the work in the manner specified by theauthor or licensor (but not in any way that suggests that they endorseyou or your use of the work).Noncommercial - You may not use this work for commercial purposes.Share Alike - If you alter, transform, or build upon this work, you maydistribute the resulting work only under the same or similar license to thisone.To view a copy of this license, 3.0/Rails 10117/03/2015

The Rails Way Rails 101 17/03/2015 4 Convention over Configuration (CoC) principle use naming conventions to automatically perform the mapping example: every model is automatically included in the controllers less code, but can be confusing to beginners can be hard to look under th