ajax: the rails way

41
Alessandro BAFFA 682075 “Advanced Technologies for the Web” course

Upload: alessandro-baffa

Post on 12-Apr-2017

2.494 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: AJAX: the Rails way

Alessandro BAFFA 682075“Advanced Technologies for the Web” course

Page 2: AJAX: the Rails way

• Ruby on Rails framework

– Introduction

– Architecture: controller, model, view

– Consideration

• AJAX

– How it works

• The Rails way

2

Page 3: AJAX: the Rails way

• “A full stack, open source Web framework”

• Written in Ruby code, a modern object-oriented language

• Model – View – Controller (MVC) based

• It uses the philosophy of “convention over configuration”, that avoids developers to spend a lot of time on configuration files

• It builds-in many utilities: full unit testing framework, generator code, support for web services, receiving e-mails, Ajax support

3

Page 4: AJAX: the Rails way

4

Page 5: AJAX: the Rails way

5

Page 6: AJAX: the Rails way

http://myUrl/store/add_to_cart/123

Name of your application

Name of the controller

Name of the controller’s action

Id of selected item (from a form)

6

Page 7: AJAX: the Rails way

• The dispatcher matches the incoming request URL with the route.rb file (automatically generated by Rails) to find the controller to call

• Once the controller is identified, a new instance of this object is created by its process() method (one instance for each request)

ActionController::Routing::Routes.draw do|map|

map.connect „:controller/:action/:id‟

map.connect „blog/:year/:month/:day‟,

:controller => “blog”,

:action => “show_post”,

:requirements => {:year, :month, :day}

end

7

Page 8: AJAX: the Rails way

• must extend ActionController::Base::ApplicationController class

• are made up of one or more actions

– actions are grouped in controller as methods instead of separated objects

8

Page 9: AJAX: the Rails way

• Controller exampleRecipeController < ApplicationController

def new

@recipe = Recipe.new

end

• The action new() creates a new, empty recipe object and assigns it to the instance variable @recipe

– Recipe class represents a row in the recipes database table

– Controller assumes there’s a view component template called new.rhtml to render

9

Page 10: AJAX: the Rails way

• Controllers don’t use an object to redirect the process to the view component or another action (ActionMapping for example), but instead use the redirect_to() method

• def sign

Entry.create(params[:entry])

redirect_to :action => "index"

end

• Controller assumes there’s a view for every method

– But you can also override this way to do

10

Page 11: AJAX: the Rails way

• Is the object-relational mapping (ORM) layer supplied with Rails

• Is the model part of the web-application framework

• "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.“ (Martin Fowler)

11

Page 12: AJAX: the Rails way

• The objects don’t specify their attribute directly, but rather infer them from the table definition

• Active Record adds the Create, Read, Update, Delete (CRUD) logic directly on the attributes

• Any changes of these operations are reflected in the Active Record objects

12

Page 13: AJAX: the Rails way

The main features:

• Automated mapping between classes and tables, attributes and columns

class Product < ActiveRecord::Base end; is automatically mapped to the “products” database table

• Associations between objects controlled by simple meta-programming macros

class Firm < ActiveRecord::Base

has_many :clients

has_one :account

belongs_to :conglomorate

end

13

Page 14: AJAX: the Rails way

• Inheritance hierarchies

class Company < ActiveRecord::Base; end

class Firm < Company; end

class Client < Company; end

class PriorityClient < Client; end

• Aggregations of value objects controlled by simple meta-programming macros

• Active Record doesn’t need any XML configuration file

14

Page 15: AJAX: the Rails way

Validation

• Active Records implement validation by overwriting

Base#validate method (or the variations validate_on_create,

validate_on_update)

• Each of these methods can inspect the state of the object

• An Errors object is automatically created for every Active Record

Page 16: AJAX: the Rails way

Exampleclass Person < ActiveRecord::Base

protected

def validate

errors.add("phone_number", "has invalid format") unless

phone_number =~ /[0-9]*/

end

end

person = Person.new("first_name" => "David","phone_number" =>

“09999999")

person.save

Page 17: AJAX: the Rails way

• So you can add a message for every kind of errors (like Struts, but here in the model)

• The errors are callable from the view by form helpers methods as:– <%= error_message_for(:product)%>

– <%= error_message_on(:product, :title)%>

Page 18: AJAX: the Rails way

• Is the view part of the web-application

• Controller assumes there’s a view template for every of its actions– RecipeController try to find automatically a template called new.rhtml

in the app/views folder of the application

• Every template has access to the local variable of the

controller

• Rails provides a lot of Helper to manage any kind of variable as request, response, header, etc..

18

Page 19: AJAX: the Rails way

• Because of the interaction between controllers and models, also the template can access to the variable of the model classes

An example:

19

Page 20: AJAX: the Rails way

20

Page 21: AJAX: the Rails way

Wikipedia gives us a definition of what is a real framework:“(..)a defined support structure in which another software project can be

organized and developed. A framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project.

(..) are designed with the intent of facilitating software development, by

allowing designers and programmers to spend more time on meeting software requirements rather than dealing with the more tedious low level details of providing a working system”

=> Ruby on Rails is a real framework

21

Page 22: AJAX: the Rails way

22

Page 23: AJAX: the Rails way

• Is not a new technology, but instead a whole of technologies

– Javascript, XML, Document Object Model (DOM), cascade style sheet (CSS), XMLHTTPRequest

• Allows you to navigate web pages while page itself sends data to the server

– you don’t have to wait for a page refresh no more

– GMail, Google Maps, Google Suggest, Flickr

23

Page 24: AJAX: the Rails way

• What does mean asynchronous?

While the system is processing you can’t do anything

24

Page 25: AJAX: the Rails way

• What does mean asynchronous?

25

Page 26: AJAX: the Rails way

• The user interface is manipulated by Javascript

• Javascript

– Refreshes the informations into the page manipulating the DOM

• CSS

– Manage the correct look and feel

• XMLHTTPRequest

– Send requests to the server asynchronously

26

Page 27: AJAX: the Rails way

• Is a sort of layer between the client browser and the server

• Is the AJAX engine that decides if manage the request itself or send it to the server

• Some of the application logic is moved to the browser

27

Page 28: AJAX: the Rails way

• Is the object that Javascript uses to communicate with the server in the background

• It is a non-standard extension originated as Microsoft-specific ActiveX component that was available in the IE (now in every browser)

• It can pull in the HTML only pieces of data rather then reloading the whole page

• HTML acts as a “container” into which inject content, using

XML data retrieved from the server

28

Page 29: AJAX: the Rails way

• Communications with the server are more efficient

• Cumulative traffic and bandwidth may be less

•User interaction can be more fluid e continuous

29

Page 30: AJAX: the Rails way

30

Page 31: AJAX: the Rails way

Some problems of AJAX:

• HTML page developers must have JavaScript technology skills

• You have to change language and add some pieces of Javascript in your template

31

Page 32: AJAX: the Rails way

• Rails has built-in support for AJAX calls

– Javascript helpers

– Javascript libraries (prototype, effects, dragdrop and

controls, application)

– Javascript code generator

32

Page 33: AJAX: the Rails way

Javascript libraries automatically included in your application JavascriptHelper

server_page.rhtmlHTML+ruby code

wraps javascript in ruby code

JavascriptGenerator

Client_page.html<HTML+Javascript>

33

Page 34: AJAX: the Rails way

• Example:<div id = “mydiv”> /*The div containing the information to

refresh*/

/*ruby code inserted to the page server side*/

<%= link_to_remote(“Do the AJAX things”,

:update => „mydiv‟

:url => {:action => :say_hello})%>

/*client side this code becomes as following*/

<a href=“#” onclick=“new

Ajax.Updater(„mydiv‟,‟/example/say_hello‟,{asynchronuos:true});

return false;”>Do the AJAX thing</a>

34

Page 35: AJAX: the Rails way

• JavascriptHelper modules provide functionalities that can be grouped in:– AJAX calls

– Document Object Model (DOM) manipulation

– Visual effects

• The most important helpers are PrototypeHelper and ScriptaculousHelper (prototype and scriptaculous are also two of the most famous javascript libraries on the web)

35

Page 36: AJAX: the Rails way

• PrototypeHelper provides callbacks that automatically have access to a javascript variable (request) which contains the XMLHTTPRequest object– You can have access to ReadyStates property included in

XMLHTTPRequest object

– uninitialized(), :loading(), :loaded(), :interactive(), :complete(), :failure(), :complete()

• For this properties the prototype library have to be included into the web page when you want to use AJAX

36

Page 37: AJAX: the Rails way

Interesting methods provided by the helpers:

• Link_to_remote(string, id, URL)– String = the text for the link (generated by JavascriptGenerator)

– Id = the id of the element in your page that will be changed

– URL = the url of the action to call<%= link_to_remote(“Do the AJAX thing”,

:update => „mydiv‟

:url => {:action => :say_hello})%>

37

Page 38: AJAX: the Rails way

Interesting methods provided by the helpers:

• Observe_field(field_id,options = {}), observes that the field with the DOM id specified by field_id and makes an AJAX call when its content have changed. The options required:

– :url, the url of action to call when the content change

– :function, instead of making a remote call to a URL, you can call a javascript function

Additional option can be:

– :frequency, (in second) at which changes to this field will be detected

38

Page 39: AJAX: the Rails way

• Prototype and scriptaculous give support for DOM manipulation and visual effects. They deliver handly shortcut for a number of often used operations.– Element.show(id), shows hidden DOM element with given id

– Element.remove(id), removes the DOM element with given id

– Sortable_element(element_id,option={}), makes the element with the given id sortable by drag-and-drop and make an AJAX call whenever any sort order is changed

– Effect.puff(element), creates the illusion that the element disappears in a gently expanding cloud of smoke

39

Page 40: AJAX: the Rails way

• The developers are not forced to write a lot of cumbersome lines of javascript code

• Javascript libraries are automatically added by the creation of the application

• JavascriptHelper gives a huge of functions that can be wraps automatically to access javascript and XMLHTTPRequest properties

40

Page 41: AJAX: the Rails way

41