RUBY ON RAILSCS 186 – Arsalan Tavakoli3/18/2008Slides adapted from CS 198 slides with thegracious permission of Armando Fox andWill SobelToday’s Agenda / Goals Evolution of the Web What is Ruby on Rails? Brief overview of Ruby Rails CRUD Active Records/Controller/Views Rendering (Too Much to List Here) Probably won’t finish it all, but serves as a goodreferenceWeb 1.0 Web 1.0: user interaction == server roundtrip Other than filling out form fields Every user interaction causes server roundtrip Every roundtrip causes full page redraw Web 1.5: user interactions without contactingserver e.g. form validation before submit e.g. selecting something from menu A causescontents of menu B to change But every roundtrip still causes full page redrawWeb 2.0 Separation of server roundtrip from page rendering Initial load of page & draw page User interaction causes background roundtrip to server Response from server “captured” and passed to aprogrammer-defined JavaScript function That function can redraw part of the page in place (usingsame mechanisms as Web 1.5) Result: “desktop-like” responsive UI’s that cancontact server Auto completion “Lazy” fetch of complicated parts of page etcWhat is Ruby on Rails? Ruby is a language that is... dynamically typed, interpreted, object-oriented,functionally-inspired Rails is a web application framework that... embodies the MVC design pattern emphasizes convention over configuration leverages Ruby language features incl. dynamic typing,metaprogramming, & object-orientation to provide elegantsupport for both goals Rails handles everything up to the point where yourcode is called And everything past the point where your codedelivers stuff to the user.A Couple of Notes We are using Rails 1.2.3, not Rails 2.0 Slight differences between the two, be carefulwhen looking at tutorials on the web. Install RoR on your computer for easieraccess InstantRails for Windows Locomotive for Mac OSx LOTS of simple ROR tutorials out there Rolling with Ruby on Rails (Revisited) is the mostpopular and a good place to startRuby Purely Object-Oriented Language EVERYTHING is an object, and EVERYTHINGhas a type Borrows from: Lisp, Perl, Smalltalk, and CLU Exists outside of Rails (but the reverse isn’ttrue) irb: Ruby’s built-in interpreter to test outcommands and test code ri: Ruby’s equivalent to ‘man’Variables A Variable in Ruby holds objects Since everything is an object, a variable can holdanything! Variable names indicate scope, not type Local Variable: foo, bar, _temp Instance Variable: @foo, @bar, @_temp Symbol: :foo, :bar, :_temp Array: [1, “1”, :one] Hash: { :one => 1, ‘two’ => 2}Review: Naming Conventions &Syntax ClassNamesclass NewRubyProgrammer ... end method_names and variable_namesdef learn_conventions ... end predicate_like_methods?def is_faculty_member? ... end Return values Each method returns a single object If no explicit return statement, then return object is that whichwas last referenced.Def return_10(v)10;End;Review: Syntax Syntax features Whitespace is not significant (unlike Python) Statements separated by semicolons or newlines Statement can span a newline* Parentheses can often be omitted** when unambiguous to parser; use caution!! raise "D'oh!" unless valid(arg) raise "D'oh!" unless valid arg✘ raise "D'oh!" unless valid(arg) Advice: use a good text editorThe MVC Design Pattern Goal: separate organization of data (model) from UI & presentation (view)by introducing controller mediates user actions requesting access to data presents data for rendering by the view Web apps are “sort of” MVC by designControllerView Model• User actions• Directives forrendering data• Read data• Update data• Data provided toviews.rb (Ruby) code.rhtml template(or .rjs, .rxml...)SQL table + Ruby classA Less Trivial Example...Let’s walk through a full (single-table) MVCexample...1. Design the model2. Instantiate the model (table & Ruby code)3. Basic controller to do CRUD (Create, Read,Update, Destroy) operations on modelSQL 001 A SQL table has a number of rows of identicalstructure Each row has several columns (fields,attributes, etc.) You can define relationships between tables(associations)—we’ll get to that later A collection of tables & relationships is called aschemaMVC in RoR: Convention overConfigurationIf data model is called Student: model (Ruby class) is app/models/student.rb SQL table is students table row = object instance columns = object methods (a/k/a object instance variables) controller methods live inapp/controllers/student_controller.rb views are app/views/student/*.erb.html and other types of views we'll meet laterPreview: CRUD in SQL 4 basic operations on a table row: Create, Read,Update attributes, DestroyINSERT INTO students(last_name, ucb_sid, degree_expected)VALUES (“Fox”, 99999, “1998-12-15”), (“Bodik”, 88888, “2009-06-05”)SELECT * FROM studentsWHERE (degree_expected < “2000-01-01”)UPDATE studentsSET degree_expected=“2008-06-05”WHERE last_name=“Bodik”)DELETE FROM students WHERE ucb_sid=99999Rails ActiveRecord models ActiveRecord, a major component of Rails... Uses SQL tables as underlying storage, and SQL commandsas underlying manipulation, of collections of Ruby objects (Later) Provides an object-relationship graph abstractionusing SQL Joins as the underlying machinery Oversimplification: 1 instance of Ruby class Foo == 1row in a SQL table called Foos Let Rails do the work of creating our model andrelated stuff:script/generate scaffold studentlast_name:string first_name:stringucb_id:integer degree_expected:datetimeCapture commonelements ofstudent-relatedviewsCRUDviewsFor creatingtest caseson studentmodel &controllerMore to notice about scaffolding identical app/models/student.rb create test/unit/student_test.rb create test/fixtures/students.yml create app/views/students/_form.rhtml create app/views/students/list.rhtml create app/views/students/show.rhtml create app/views/students/new.rhtml create app/views/students/edit.rhtml create app/controllers/students_controller.rb create test/functional/students_controller_test.rb create
View Full Document