rails & ajax module 5. introduction to rails overview of rails rails is ruby based “a...

25
Rails & Ajax Module 5

Upload: esmond-richards

Post on 05-Jan-2016

248 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Rails & Ajax

Module 5

Page 2: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Introduction to Rails

Page 3: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Overview of RailsRails is Ruby based“A development framework for Web-based applications”Rails uses the Model-View-Controller architecture

Model classes are the data classes, including constraint enforcement

View classes present the data to the userController classes perform computations and deal with user

interactionRails uses an Object-Relational Mapping approach to

working with databasesA cars table corresponds to a car classThe rows of the table correspond to instances of the classThe correspondence is built automatically by the Rails

frameworkRails uses a combination of Ruby code and template files

to create responses

Page 4: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Developer TasksDesign and build the model, including a

database for storing model dataDesign and implement actionsDesign and implement the views

Page 5: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Document requestsThe Rails framework provides much of the

superstructure necessary for a web application

Scripts with the Rails framework set up the basic structure

The first Rails example serves a single static document

Page 6: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Project SetupThe InstantRails package provides all the

components needed to develop and test Rails projects on a Microsoft Windows platform

Start the InstantRails consoleInstantRails

Set up a rails application rails rails1

Generate a controllerruby script/generate controller say

Run the default serverruby script/server

The server runs for a particular application

Page 7: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Project Directory Structure

Page 8: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Project ComponentsA controller class, SayController, in the controllers directory

The controller class has method named hello

An html template file (static for this example) named hello.rhtml in directory views\say

The Rails framework associates these components by the name ‘say’

Page 9: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Request Processing

Page 10: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Dynamic DocumentsThe next example displays the greeting but

also displays the current timeUses Time.now from the Ruby library

<% … %> embeds Ruby code in template files<%= … %> causes the value of the

executed code to be inserted in placeInstance variables of the controller class

can be accessed in the template file

Page 11: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Setting Up the ApplicationsA controller home is createdAn empty action method the_form is

createdA static template file the_form.rhtml is

created to display the initial data entry form

The action on the form is simply “result” which links to an action method named result in the same controller class

Page 12: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

The Controller and the ViewAction method result in the controller class

Get form dataCompute results

Object params holds the form data in a hash-like objectCan be indexed by symbols or by strings using

widget namesparams[:phone] gets the phone numberparams[:unpop].to_i gets the unpopped amount

as an integerThe sprintf method can be used to format data

Used with format specification %5.2d to format floating numbers with exactly two decimal places

Page 13: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Building the DatabaseA database is created with four tables using

MySQL commandsA script file is used to make the typing easierTables are named with plural names because

of Rails names corresponding classes with the singular

Model classes are createdruby script/generate model corvette

Directives in the model files specify the table relationshas_manybelongs_to

Page 14: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Building the ApplicationA table object gives access to the data in the table

Method count gives the number of rowsMethod find is used to search

Method findOne parameter is a primary key search. The matching

row is returnedParameter :all requires a second parameter giving the

value of the :conditions symbol, a test condition. All matching rows are returned

Parameter :first requires a second parameter giving the value of the :conditions symbol, a test condition. The first matching row is returned

Method find_by_sql takes an SQL SELECT commandThe action methods query the database and put

results into instance variablesThe matching template displays the results

Page 15: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

LayoutsA layout template provides a standard

template for other templatesPut in the layouts directoryPut a layout command in the ApplicationController class

The layout template can provide header and styling directions while other templates provide content

The @content_for_layout variable in the layout template provides the content from the other template

Page 16: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

AJAX

Page 17: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Overview of AjaxAjax is not an API or a programming languageAjax aims to provide more responsive web

applicationsIn normal request/response HTTP cycles, the

browser locks waiting for the response and an entire page must be displayed

With Ajax, asynchronous requests may be made and responses are used to update part of a pageUser can continue to interact with a page while the

request is in progressLess data needs to be transmittedPage update is quicker because only a part of a page

is modified

Page 18: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Approaches to AjaxThe iframe element can be hidden and it

allows asynchronous requests to a serverJavascript support allows updating other

elements of the page from the frame responseMicrosoft introduced the XmlDocument and

XMLHTML objects which are used to make asynchronous requests directly from JavaScriptOther browsers followed this pathMost browsers now name the object

XMLHttpRequest

Page 19: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

The Form DocumentThe trigger for the request is a blur event

on the zip code widgetthis.value is used by the handler to get the

zip code value enteredAll relevant widgets have the id attribute

set for easy access in the JavaScript

Page 20: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

The Request PhaseTwo functions

blur event handlerResponse processor

An XMLHttpRequest object is used to create the request

A callback is a function called when a response is receivedFunction receivePlace is the callbackThe function name is assigned to a property of

XMLHttpRequestThe open method sets up the request

Method parameter, either “GET” or “POST”URL parameter with zip code in the URLA parameter signifying asynchronous or not

The send method sends the requestThe getPlace method implements this

Page 21: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

The Receiver PhaseThe function that parses the response must

have access to the XMLHttpRequest objectThis cannot be global since there may be

multiple outstanding requests at any timeThe callback becomes an anonymous function

which is defined in the getPlace method and keeps references to the XMLHttpRequest object held in a local variable

The response handler only acts if the readyState is 4, meaning the response is complete

Page 22: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Cross-Browser SupportOlder Microsoft browsers uses a different

approach to getting the request objectTesting the existence of window.XMLHttpRequest differentiates the browsers

In the older browsersnew ActiveXObject(“Microsoft.XMLHTTP”)

creates the object needed

Page 23: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Rails with AjaxThe prototype JavaScript library is integrated into

Rails<%= javascript_include_tag “prototype” %>Rails and Ajax have some limitations

Not all elements can be modified, depending on the browser

The div element can be modifiedRails and Ajax process

Sequence is triggeredData is sent asynchronously to an action handlerThe action handler creates a responseJavaScript in the browser interprets the response

Page 24: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

Triggering AjaxRuby provides methods to set up triggers for Ajax

processinglink_to_remote triggers when a link is activatedobserve_field is triggered when a widget is changed

Method observe_fieldTakes the name of the widget as a first paramaterSeveral ‘keyword’ parameters

:url where to post, often associated with an :action symbol definition

:update associated to the id of the elment whose value is to be changed in response

:with specifies a parameter for the HTTP request:frequency specifies how often to check:complete, :success, :failure associate with callbacks used

depending on the outpcome of the reuqest

Page 25: Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the

The ControllerThe fill_city_state method is added to the

controller to handle the asynchronous request

The render method is used to create the content of the response since it is simple text