125
Web 2.0 Application Development make your webapps more social Amit K Mathur [email protected] http://www.magnionlabs.com Web 2.0 Application Development – p. 1

Web 2.0 Application development with Ruby on Rails

Embed Size (px)

Citation preview

Page 1: Web 2.0 Application development with Ruby on Rails

Web 2.0 ApplicationDevelopment

make your webapps more social

Amit K Mathur

[email protected]

http://www.magnionlabs.com

Web 2.0 Application Development – p. 1

Page 2: Web 2.0 Application development with Ruby on Rails

Trainer

Independent consultant and freelance developer

http://www.magnionlabs.com/blog Follow me on Twitter:

@akmags

Reachable also on:

� Skype (akmags) and

� Cell (+91 99863 95538).

Web 2.0 Application Development – p. 2

Page 3: Web 2.0 Application development with Ruby on Rails

You

� Have you done web

development before?

Which platform?

� What do you expect to

gain out of this train-

ing? Build an app?

Web 2.0 Application Development – p. 3

Page 4: Web 2.0 Application development with Ruby on Rails

Goals of this training

� Introduction to the medley of technologies in

web dev

� How to take advantage of some of emerging

web 2.0 techniques

Web 2.0 Application Development – p. 4

Page 5: Web 2.0 Application development with Ruby on Rails

Rules

� Flames, abuse, questions? Welcome any time

� Use the “make sure you cover” sheet

� Hands on work - no rush to finish

� 4 days

Web 2.0 Application Development – p. 5

Page 6: Web 2.0 Application development with Ruby on Rails

Day 1

� Web 2.0 - definition

� Review of Webapp architecture

� Set up system for hands on exercises

� Review of Ruby

� RoR Introduction

Web 2.0 Application Development – p. 6

Page 7: Web 2.0 Application development with Ruby on Rails

Day 2

� Developing Quiz app with Rails

� Rails theory

� RESTful architecture

Web 2.0 Application Development – p. 7

Page 8: Web 2.0 Application development with Ruby on Rails

Day 3

� AJAX with Rails

� Enhance Quiz app

� Javascript, Jquery

Web 2.0 Application Development – p. 8

Page 9: Web 2.0 Application development with Ruby on Rails

Day 4

� Feeds, Microformats

� Mashup - develop an example app

� Tag cloud, Reverse AJAX

� Flash

� The End

Web 2.0 Application Development – p. 9

Page 10: Web 2.0 Application development with Ruby on Rails

Let’s start..

6560

Web 2.0 Application Development – p. 10

Page 11: Web 2.0 Application development with Ruby on Rails

Web is young

6560

Approximate number of days since Tim Berners-Lee’s first

public webpage (Aug 6, 1991)

Great achivements: Google, Wikipedia, Amazon,

ebay, online banking, etc.

Web 2.0 Application Development – p. 11

Page 12: Web 2.0 Application development with Ruby on Rails

Web - beginning

� Web pages as “Shared documents” - send a

request to server, get a document back (HTTP)

� headed towards "Sematic Web" - a web of data

Web 2.0 Application Development – p. 12

Page 13: Web 2.0 Application development with Ruby on Rails

Web - the new goal

Semantic Web - web of data� A page is atomic to computers but not to a

human

� structures so that machines can recognize the

data on the page

Web 2.0 Application Development – p. 13

Page 14: Web 2.0 Application development with Ruby on Rails

Web 2.0

A small step towards semantic web

� “sharing” and “data” are now more important

� site’s importance increases as user

participation increases

Web 2.0 Application Development – p. 14

Page 15: Web 2.0 Application development with Ruby on Rails

Web 2.0

The Web 2.0 dilemma

Web 2.0 Application Development – p. 15

Page 16: Web 2.0 Application development with Ruby on Rails

Web 2.0

� Social: database grows in importance as user

participation increases

� Site is just a platform

• delicious.com, flickr.com, twitter, digg,

Google maps, uservoice.com, picnik.com

• See it in action:

� http://del.icio.us/popular

� http://delicious.com/tag/programming+development

Web 2.0 Application Development – p. 16

Page 17: Web 2.0 Application development with Ruby on Rails

Web 2.0

� Architectural: scaling, RESTful, microformats

� Security is paramount since data is important

� Frivolous and incidental: drop shadows, beta

tag (eg. ajax-loader.com), vowel-less names,

AJAX, tagging

Web 2.0 Application Development – p. 17

Page 18: Web 2.0 Application development with Ruby on Rails

Web 2.0

Reference: James Surowiecki, The Wisdom of

Crowds: Why the Many Are Smarter than the Few

and How Collective Wisdom Shapes Business,

Economies, Societies, and Nations. Published by:

Random House, 2004.

Web 2.0 Application Development – p. 18

Page 19: Web 2.0 Application development with Ruby on Rails

Webapp architecture

HTTP

Response

HTML doc

Javascript

CSS

construct

a page

/path/to/action

if(...) ... ...else ... ...end

Request

http://www.example.com/path/to/action

Server Clientwww.example.com

DB

Application Server

Web 2.0 Application Development – p. 19

Page 20: Web 2.0 Application development with Ruby on Rails

Web development

Browser Framework� When user types an address, browser sends a

HTTP GET (or POST) request to server

� Server send back a response

• 1xx (Informational)

• 2xx (Success)

• 3xx (Redirect)

• 4xx (Client Error)

• 5xx (Server Error) Web 2.0 Application Development – p. 20

Page 21: Web 2.0 Application development with Ruby on Rails

Web development

� Response is text

• formatted as HTML

• CSS file specifies layout

• Javascript, which is executed as code by the

browser

Theory over!

Web 2.0 Application Development – p. 21

Page 22: Web 2.0 Application development with Ruby on Rails

Hands on work

Set up your system� Linux Desktop

� install Ruby 1.8.6 (or

1.8.7)

� install Rubygems

� sudo gem install rails

Take a break!

Web 2.0 Application Development – p. 22

Page 23: Web 2.0 Application development with Ruby on Rails

Dekho

� http://yellowpages.com

� http://www.hulu.com

� http://revolutionhealth.com

� http://www.twitter.com

� http://basecamphq.com

� http://43things.com/

� http://penny-arcade.com/

These are all powered by Ruby on RailsWeb 2.0 Application Development – p. 23

Page 24: Web 2.0 Application development with Ruby on Rails

Web development

It can get overwhelming.

� graphic design

� HTML/CSS

� Javascript/AJAX

� RIAA/Flash

� HTTP

� Server side development

� Database design

� Analytics & operation

Rails makes it easy. Really.

Web 2.0 Application Development – p. 24

Page 25: Web 2.0 Application development with Ruby on Rails

Ruby on Rails

� Ruby is a (very powerful) general purpose

programming language

� Ruby on Rails is a framework to write web

applications in Ruby

Web 2.0 Application Development – p. 25

Page 26: Web 2.0 Application development with Ruby on Rails

Ruby on Rails

� Ruby on Rails is

sometimes shortened

to just Rails

� Ruby on Rails is more

of a DSL for web-apps

� full stack framework

Web 2.0 Application Development – p. 26

Page 27: Web 2.0 Application development with Ruby on Rails

Database backed web application

Web application which provides interface to an

underlying database

� Examples are plentiful

• Gmail, Airline ticketing system like

cleartrip.com , flickr,

• and almost any webapp these days...

� Non examples are: chat systems, mortgage

calculators, etc.

Web 2.0 Application Development – p. 27

Page 28: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Say, Hi!

� History: Originated in

Japan

� created by Yukihiro

Matsumoto (aka Matz)

Web 2.0 Application Development – p. 28

Page 29: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Personality� An easy to learn OO scripting language

� Influenced by Perl, Smalltalk, CLU, OCaml,

Dylan and others

� VHLL, Simpler, better OO

� Superb Regex support

� Interpreted (Code, test, tinker cycle is shorter) -

even declarations are executed,Web 2.0 Application Development – p. 29

Page 30: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Personality� Agile language - changes are less painful

� GC

Programming should be enjoyable -

Ruby is optimized for humans - Matz.

Web 2.0 Application Development – p. 30

Page 31: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Is it Strongly typed or weakly typed

� it depends. Ruby supports duck typing

Web 2.0 Application Development – p. 31

Page 32: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Basic OO concepts� fundamental unit is an object: container of data

and methods to access this data

� attributes and methods

� Object is an instance of a Class; Class is a

blueprint for creating Objects; complex type

than Integer or String

Web 2.0 Application Development – p. 32

Page 33: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Basic OO concepts� Class can also have class attributes - shared

amongst all the objects

� Inheritance: is-a relationship; means of

extending functionality - achieves code reuse

� Polymorphism

� Abstract Class (can only be inherited from),

Concrete Class

Web 2.0 Application Development – p. 33

Page 34: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Syntax� no semicolon needed

� line beginning with # is a comment

Web 2.0 Application Development – p. 34

Page 35: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Syntax� data types:

• Integers, String (can be double quoted or

singly quoted), Array, Hash

• Symbols are names of variables. e.g.

:question, :user

• Read them as the thing called question

• Symbols are constants - hence, can be used

as enumsWeb 2.0 Application Development – p. 35

Page 36: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Everything, including a literal, is an object, so this

works:

-15.abs

"mera bharat mahan".length

"Venkat".index("n")

"We are like this only!".downcase.split(//).sort.uniq.join

� Variables don’t have any type, only objects

have type

Web 2.0 Application Development – p. 36

Page 37: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Variable naming convention is important - denotes

scope

� All constants & Class names begin with a

capital letter (e.g. PI, Vehicle)

� All local variables begin with a lower case (e.g.

sum_total, nn)

Web 2.0 Application Development – p. 37

Page 38: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Iteration of enumerable objects

# An array with some elements

arr = [1, 2, 3, 5,

:lemme_see, 13,

"is it Fibonacci or what"]

arr.each do |e|

puts e

end

Web 2.0 Application Development – p. 38

Page 39: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

# output

1

2

3

5

lemme_see

13

is it Fibonacci or what

Web 2.0 Application Development – p. 39

Page 40: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Mutation is also easy

arr.map { |e| e.to_s }

["1", "2", "3", "5", "lemme_see",

"13", "is it Fibonacci or what"]

Web 2.0 Application Development – p. 40

Page 41: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

capitals = { "Karnataka" => "Bangalore",

"Kerala" => "Thiruvananthapuram", "A.P."

capitals.keys # ["Karnataka", "A.P.",

"T.N.", "Kerala"]

capitals.values # ["Bangalore", "Hyderabad",

"chennai", "Thiruvananthapuram"]

capitals["T.N."] # Chennai

capitals["Kerala"] = "Trivandrum"

Web 2.0 Application Development – p. 41

Page 42: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Loops and branches

if temp > 30

puts "It’s very hot"

else

puts "I can bear it"

end

puts "Pass me a glass of water" if temp

Web 2.0 Application Development – p. 42

Page 43: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

case "Web application development"

when "some value"

puts "Branch 1"

when "different value"

puts "Branch 2"

when /char/

puts "Branch 3"

else

puts "Branch 4"

endWeb 2.0 Application Development – p. 43

Page 44: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Exercise: write a Ruby program� Given a string of tags - each tag is a word,

separated by comma - find whether a given tag

exists in the tag list

� Find whether all of a list of tags (given as

string), exists in a tag list

Web 2.0 Application Development – p. 44

Page 45: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Exercise: hintstags = "social,friend,comic,fun"

tags.split(",").find { |t|

t == ’social’

}

Web 2.0 Application Development – p. 45

Page 46: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

OO in Ruby� Declare a class

� public, private and protected visbility

� No multiple inheritance

� Package namespace

Web 2.0 Application Development – p. 46

Page 47: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

class Rectangle < GeometricShape

def set_length(l)

@length = l

end

def set_width(w)

@width = w

end

def area

@length * @width

end

protected

def calculate_sides

end

end

Web 2.0 Application Development – p. 47

Page 48: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

OO contd.� Duck Typing: Behaviour is more important

than inheritance

� Classes are Open - Methods can be added any

time to any class even to built-in, library ones

Web 2.0 Application Development – p. 48

Page 49: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Exception HandlingWays to throw an exception

raise "this is an Exception"

raise ArgumentError.new(

"Illegal value for #{i}th argument")

Web 2.0 Application Development – p. 49

Page 50: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Handling one

begin

# do something

rescue ArgumentError => e

# do the firefighting

retry # start the begin block again

ensure

# clean up - executed always

end

Web 2.0 Application Development – p. 50

Page 51: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Modules� defines a namespace

� mixins - instance methods of modules become

instance methods of the class

Web 2.0 Application Development – p. 51

Page 52: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Tools� Rdoc for online documentation

� irb for testing your scripts quickly

Web 2.0 Application Development – p. 52

Page 53: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Other miscellany:parenthesis are optional with method calls

foo(a, b, c)

foo a, b, c

passing hash to a method if its the only parameter

does not require braces

foo(a => 1, b => 2)

# is really foo({a => 1, b => 2})

Web 2.0 Application Development – p. 53

Page 54: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

Other nitty gritty� In nested if ladder, elsif is used instead of else if

� method names can end in ! (object itself is

modified) or ? (method returns a boolean

value)

� there are no ++ or - - operators

� everything is true except false and nil. 0, "", []

are all true

Web 2.0 Application Development – p. 54

Page 55: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

� inside a string, anything within # is an

expression

def do_something(param1, param2)

result = hello()

puts "The result of compuation is #{result.capitalize}"

return result if xxx

end

Web 2.0 Application Development – p. 55

Page 56: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

More nitty gritty

� variables don’t have classes, only values have

classes

� there are both &&, || and ’and’, ’or’ operators.

and, or have a lower precedence

� variable and method names may not be always

distinguishable by eye

Web 2.0 Application Development – p. 56

Page 57: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

� Ruby allows aliasing - giving a method other

names

vowels = [’a’, ’e’, ’i’, ’o’, ’u’]

# following are the same method

vowels.size

vowels.length

Web 2.0 Application Development – p. 57

Page 58: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

yet more nitty gritty� powerful range operator (.. and ...)

� multiple assignment is allowed

a,b = b,a # easy peasy swap

� regex are very powerful (if you know Java or

Perl ones, you are good)

Web 2.0 Application Development – p. 58

Page 59: Web 2.0 Application development with Ruby on Rails

Romancing with Ruby

OK, that’s it!Web 2.0 Application Development – p. 59

Page 60: Web 2.0 Application development with Ruby on Rails

Day 2

� Developing Quiz app with Rails

� Rails theory

� RESTful architecture

Web 2.0 Application Development – p. 60

Page 61: Web 2.0 Application development with Ruby on Rails

An itch to scratch

Problem statement:A database of multiple choice questions and

answers. Every visitor can take a quiz, which is a

random set of 10 questions. Then they see how

many they got correct.

Bells and whistles: For registered users, let them

see the history of all quizzes played. Display a

global list of top scrorers, etc.

Web 2.0 Application Development – p. 61

Page 62: Web 2.0 Application development with Ruby on Rails

Page flow diagram

� Admin interface (enter questions)

� External interface (home page, play a round,

results page)

Web 2.0 Application Development – p. 62

Page 63: Web 2.0 Application development with Ruby on Rails

DB table

questions table

� qtext:string

� option1:string to

option4:string

� answer:integer

Not fully normalized, but let’s go with it.

Web 2.0 Application Development – p. 63

Page 64: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� rails quiz –database=mysql

� cd quiz

� ruby script/generate scaffold question

qtext:string option1:string option2:string

option3:string option4:string answer:integer

Web 2.0 Application Development – p. 64

Page 65: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

Framework for the fatafat

generation

Framework = lots of

needed code is already in

place. start by filling in the

business logic

Web 2.0 Application Development – p. 65

Page 66: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� app contains all application code and test

should have all the tests for this code

� any static files go into public

� note config, db, log and script directories

� Rakefile has many useful tasks defined (rake

-T)

� default webserver is WEBrick. In production, it

should be replaced by something more

powerful like mongrelWeb 2.0 Application Development – p. 66

Page 67: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� rake db:create

� rake db:migrate

� many DBs are sup-

ported: MySQL, DB2,

Oracle, Postgres,

SQLServer, SQLite,

etc.

Web 2.0 Application Development – p. 67

Page 68: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� ruby script/server

� http://localhost:3000/questions

� create, edit, delete

questions

Web 2.0 Application Development – p. 68

Page 69: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

What’s this scaffolding

thing...

� a bare but functional

interface with zero

programming

� a good starting point

for a piece by piece re-

placement to build the

real appWeb 2.0 Application Development – p. 69

Page 70: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� built around CRUD features of a model

� controller provides CRUD methods

� model database schema provided by migration

script

� Database table was looked up from

config/database.yml

Web 2.0 Application Development – p. 70

Page 71: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

MVC� Model = state of the application, often saved

into DB with all business rules

� Controller = receive events from outside world,

interact with model and present suitable view

� View = suitable presentation of model for user

interaction

Web 2.0 Application Development – p. 71

Page 72: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

Exercise: Add authorization - only admin should

be able to view these pages

Look at restful_authentication plugin

Still stuck? Have you tried http://www.stackoverflow.com

Web 2.0 Application Development – p. 72

Page 73: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

A DSL for creating

Database backed ap-

plication. Where actions

and forms can be mapped

directly to database

Web 2.0 Application Development – p. 73

Page 74: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

ActiveRecord� ORM - map database tables to objects

� Maps DB table to class, rows to objects,

columns to attributes with accessors

(getters/setters) defined

Web 2.0 Application Development – p. 74

Page 75: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

ActiveRecord� near zero configuration - if you follow the

convention� Powerful operations:

order = Order.find(1)

orders = Order.find(:all, :conditions => ["name = ?", "Dave"])

orders.each do |o|

o.price *= 0.15

o.save

end

Web 2.0 Application Development – p. 75

Page 76: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

ActiveRecord� empty description should not be allowed

class Question < ActiveRecord::Base

validates_presence_of :qtext

end

Did you note that after making any changes we never have to restart out application -

changes are picked up automatically

Web 2.0 Application Development – p. 76

Page 77: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

Error handling in forms� Notice that forms highlight the fields in error

� When a validation fails, ActiveRecord puts the

error message with the model object

� Controller or view can access themunless question = Question.create(params[:question])

validation_error = question.errors.on(:qtext)

end

Web 2.0 Application Development – p. 77

Page 78: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

Error handling in forms� views display all the error messages in a box

using

<%= error_messages_for :question %>

Web 2.0 Application Development – p. 78

Page 79: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

Routing� all incoming requests are mapped to an actionin a controllerhttp://localhost:3000/questions/2/edit = controller/id/action

� other path info in URL, or URL parameters,

put in params hash

Web 2.0 Application Development – p. 79

Page 80: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

RESTful architecture� RESTful controllers

� easier to code and test

� more scalable

� simple

� may be hard to understand and apply

Web 2.0 Application Development – p. 80

Page 81: Web 2.0 Application development with Ruby on Rails

REST

� style of architecting networked applications

� is not RPC

� heavily based on HTTP and the Web

� is not design

Web 2.0 Application Development – p. 81

Page 82: Web 2.0 Application development with Ruby on Rails

REST

RPC - web based mailbox

[id, body , [id,body], ..] = getAllMails()

[id, body , [id,body], ..] = getAllUnreadMails()

� id = createNewMessage(body, recipient-emailid)

� archiveMail(id)

� deleteMail(id)

� addLabel(id, label)

Web 2.0 Application Development – p. 82

Page 83: Web 2.0 Application development with Ruby on Rails

REST

REST Triangle� Nouns (URI)

� Verbs (GET, POST, PUT and DELETE)

� Content-Type (Representation)

Web 2.0 Application Development – p. 83

Page 84: Web 2.0 Application development with Ruby on Rails

REST

REST - web based mailbox� Identify nouns

• /mails – All mails

• /mails/unread – All unread mails

• /mails/:id – A particular mail

• /mails/:id/archived – archive flag of that

particular mail

• /mails/:id/labels – all labels for that mail

Web 2.0 Application Development – p. 84

Page 85: Web 2.0 Application development with Ruby on Rails

REST

REST - web based mailbox

� GET /mails

� GET /mails/unread

� POST /mails

� PUT /mails/:id/archived

� DELETE /mails/:id

� POST /mails/:id/labels

Ref: http://rest.blueoxen.net/cgi-bin/wiki.pl?RestInPlainEnglish

Web 2.0 Application Development – p. 85

Page 86: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

Rails Philosophy� DRY (every piece of knowledge is expressed in

just one place)

� COC (sensible defaults)

� Rails is Agile (quick turnarounds, testing is

intertwined)

� It’s fun (don’t tell anyone ;-))

Web 2.0 Application Development – p. 86

Page 87: Web 2.0 Application development with Ruby on Rails

Day 3

� AJAX with Rails

� Enhance Quiz app

� Javascript, Jquery

Web 2.0 Application Development – p. 87

Page 88: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

AJAXify the add a question formMove “add a question” form on the index page and

save without reload

Web 2.0 Application Development – p. 88

Page 89: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

AJAXify the add a question form

� create _question_form partial from

new.html.erb and call that partial from

index.html.erb (and new.html.erb)

� initialize @question in

QuestionsController#index (as in

QuestionsController#new)

Web 2.0 Application Development – p. 89

Page 90: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� redirect_to questions_url in

QuestionsController#create

� change form_for to

remote_form_for(@questions) in

index.html.erb

Web 2.0 Application Development – p. 90

Page 91: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� add id (questions_list) to table in

index.html.erb

� from table row in for loop in index.html.erb,

extract partial _question and call that from

index

<%= render :partial => ’question’, :object => question %>

� add javascript_include_tag :defaults to

questions.html.erb layoutWeb 2.0 Application Development – p. 91

Page 92: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

� QuestionsController#create add js block:format.js {

render :update do |page|

page.replace_html(’question_form’,

:partial => ’question_form’,

:locals => { :question => Question.new })

page.insert_html(:bottom, ’questions_list’,

:partial => ’question’, :object => @question)

end

}

Web 2.0 Application Development – p. 92

Page 93: Web 2.0 Application development with Ruby on Rails

Rolling on Rails

RJS - Ruby to Javascript� we didn’t write any Javascript code

� look at the calls to prototype library that was

generated (index.html)

Web 2.0 Application Development – p. 93

Page 94: Web 2.0 Application development with Ruby on Rails

RJS siblings

� Java to Javascript translation

• GWT

• DWR - also supports reverse AJAX

Web 2.0 Application Development – p. 94

Page 95: Web 2.0 Application development with Ruby on Rails

Web resources

Ruby:

� http://www.ruby-lang.org

� http://www.rubycentral.com/pickaxe

� http://rubyforge.org

� http://rubygems.org

� http://ruby.alltop.com/

Rails:� http://rubyonrails.org

� http://api.rubyonrails.org

Web 2.0 Application Development – p. 95

Page 96: Web 2.0 Application development with Ruby on Rails

Books

� Programming Ruby, The Pragmatic

programmer’s Guide, 2 ed. aka Pickaxe

Ruby book by Dave Thomas et al.

� The Ruby way by Hal Fulton.

� Agile Web Development with Rails, 2nd

Edition by Dave Thomas, David Heine-

meier Hansson, et al.

Web 2.0 Application Development – p. 96

Page 97: Web 2.0 Application development with Ruby on Rails

More on AJAX

Basically, what "Ajax" means is "Javascript now works."

- Paul Graham

Various styles of Doing AJAX:

� XmlHttpRequest object (Javascript libraries)

� dynamic script tags (static JS generates

javascript and evals)

� iframes

Web 2.0 Application Development – p. 97

Page 98: Web 2.0 Application development with Ruby on Rails

Javascript toolkits

� Javascript libraries: prototype,

scriptaculous, Jquery, Dojo, ExtJS and

many more

� unobtrusive JS (no onclick on mixing JS

inside HTML - all JS outside in a

separate file - maintenance is easier,

graceful degradation for non JS browsers

� common features of toolkits (Effects,

traversal, AJAX, enhanced controls)

Web 2.0 Application Development – p. 98

Page 99: Web 2.0 Application development with Ruby on Rails

Jquery

� cross browser

� CSS style selectors for

traversal

� slick effects

� thriving ecosystem of plug-

ins

Web 2.0 Application Development – p. 99

Page 100: Web 2.0 Application development with Ruby on Rails

Jquery

<html>

<head>

<script

src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"

type="text/javascript">

</script>

<script type="text/javascript">

$(document).ready(function(){

// Your code here

});

</script>

</head>

<body>

<p class="note">I am excited to step into the cyberspace.</p>

<p class="greeting"><a href="#">Hello World!</a></p>

</body>

</html>

Web 2.0 Application Development – p. 100

Page 101: Web 2.0 Application development with Ruby on Rails

Jquery

CSS style selectors$(".greeting a").click(function(event){

alert("Welcome!");

});

Web 2.0 Application Development – p. 101

Page 102: Web 2.0 Application development with Ruby on Rails

Jquery

Add CSS class<!-- Add to head section -->

<style type="text/css">

.grey { color: #aaa }

</style>

$(".greeting a").click(function(event){

$(".note").addClass(’grey’);

});

Web 2.0 Application Development – p. 102

Page 103: Web 2.0 Application development with Ruby on Rails

Jquery

Effects$(".greeting a").click(function(event){

$(".note").slideToggle();

});

Web 2.0 Application Development – p. 103

Page 104: Web 2.0 Application development with Ruby on Rails

Jquery

Plugin - tablesorter<!-- add to head section -->

<script src="http://tablesorter.com/jquery.tablesorter.min.js"

type="text/javascript">

</script>

<!-- replace p.note -->

<p class="note">I am excited to step into the cyberspace.

<table border="1">

<thead><th>Name</th><th>Message</th></thead>

<tr><td>Alan Turing</td><td>Theoretical formulation</td></tr>

<tr><td>Jon Von Neumann</td><td>Stored-program architecture</td></tr>

<tr><td>ARPA</td><td>Internet</td></tr>

<tr><td>Tim Berners Lee</td><td>World Wide Web</td></tr>

</table>

</p>

Web 2.0 Application Development – p. 104

Page 105: Web 2.0 Application development with Ruby on Rails

Jquery

Plugin - tablesorter<!-- call Jquery tablesorter -->

$(".note table").tablesorter();

� Many many great plugins

� Makes Javascript accessible and fun!

Web 2.0 Application Development – p. 105

Page 106: Web 2.0 Application development with Ruby on Rails

Day 4

� Feeds, Microformats

� Mashup - develop an example app

� Tag cloud, Reverse AJAX

� Flash

Web 2.0 Application Development – p. 106

Page 107: Web 2.0 Application development with Ruby on Rails

Feeds

� Important since data

is the king in Web 2.0

� can be read in feed

readers like Google

reader or iGoogle,

Netvibes, PageFlakes

� popularized by blogs

Web 2.0 Application Development – p. 107

Page 108: Web 2.0 Application development with Ruby on Rails

Feeds

� used in web app operations, news and stock

ticker,

� converted to email, stored in databases, or

mashed

� Many different formats: RSS 0.91, RSS 2.0,

ATOM, RDF: but they all work with popular

feed readers. So, not a problem

Web 2.0 Application Development – p. 108

Page 109: Web 2.0 Application development with Ruby on Rails

Feed

How they work� poll to check for new content:

� creating feeds: manual, automatic

� homework: create a feed for questions - many

admins adding questions, keep a feed of edits

(keep a feed of users playing quizzed at your

site)

Web 2.0 Application Development – p. 109

Page 110: Web 2.0 Application development with Ruby on Rails

Mashups

Web 2.0 Application Development – p. 110

Page 111: Web 2.0 Application development with Ruby on Rails

Mashups

� remember data is the king in Web 2.0: feeds or

APIs expose data, combine them to create new

apps

� Yahoo pipes

� Google maps mashups

� http://www.programmableweb.com :

mashups directory

Web 2.0 Application Development – p. 111

Page 112: Web 2.0 Application development with Ruby on Rails

Terminology

� SOA (instead of one executable, have several

applications which communicate over the

network),

� REST (an architectural style for building

networked apps - different from SOAP or RPC)

� SOAP: much like RPC - expose methods to be

called

Web 2.0 Application Development – p. 112

Page 113: Web 2.0 Application development with Ruby on Rails

Terminology

� REST: URI, fixed verbs (GET, POST, PUT,

DELETE) and content-type

� Twitter’s API is RESTful

� Amazon’s ECS (affilicate API) is SOAP

Web 2.0 Application Development – p. 113

Page 114: Web 2.0 Application development with Ruby on Rails

Mashup Exercise

Mashup Google maps and Twitter� Sign up for Google maps API

(http://code.google.com/apis/maps/signup.html)

� get a key

� Twitter - get all followers:

curl ’http://twitter.com/followers/ids/akmags.json’

Web 2.0 Application Development – p. 114

Page 115: Web 2.0 Application development with Ruby on Rails

Mashup Exercise

Mashup Google maps and Twitter� Get details with location of user:

curl ’http://twitter.com/users/show/54126460.json’

� Get Lat Long of a location in JSON format:

curl

’http://maps.google.com/maps/geo?q=Bangalore&output=json&oe=utf8&sensor=false&key=abcdef

� Google maps HTML example:

http://code.google.com/apis/maps/documentation/introduction.html

Web 2.0 Application Development – p. 115

Page 116: Web 2.0 Application development with Ruby on Rails

Microformats

� Ways of encoding data in HTML/XML which

is widely understood

� examples: contact details, geographic info,

calendar/event, rel=nofollow (proposed by

Google)

� use class or rel attribute which is already valid

HTML

Web 2.0 Application Development – p. 116

Page 117: Web 2.0 Application development with Ruby on Rails

Microformats

�� Google indexes and

displays uf separately

� Browser plugins acts on

them

� Operator for Firefix,

Oomph for IE

� picoformats (twitter @)

Web 2.0 Application Development – p. 117

Page 118: Web 2.0 Application development with Ruby on Rails

Tag cloud

Visual representation of

tags

Exercise: Add tags to ques-

tions in quiz app and show

a tag cloud

Web 2.0 Application Development – p. 118

Page 119: Web 2.0 Application development with Ruby on Rails

Reverse AJAX

� Push technology

� comet

� slow load

� eg. AppJet Framework used for etherpad

(http://www.etherpad.com)

Web 2.0 Application Development – p. 119

Page 120: Web 2.0 Application development with Ruby on Rails

Flash

� tool for creating interactive and animated Web

sites.

� uses vector graphics - can be scaled to any size

without losing clarity/quality

� does not require programming skills and is

easy to learn

Web 2.0 Application Development – p. 120

Page 121: Web 2.0 Application development with Ruby on Rails

Flash

Preferable to animated images andJava applets

� loads faster

� allows interactivity

� > 96% browsers have flash preinstalled

� Video sharing, games sites use flash

(youtube.com, flash-game.net etc.)

Web 2.0 Application Development – p. 121

Page 122: Web 2.0 Application development with Ruby on Rails

Flash

� Need a flash program to create flash content

(eg. Adobe Flash Lite)

� Save as ’.swf’ movie, upload to web-server

� Minimum HTML code to embed it on yourpage<object width="550" height="400">

<param name="movie" value="somefilename.swf">

<embed src="somefilename.swf" width="550" height="400">

</embed>

</object>

Web 2.0 Application Development – p. 122

Page 123: Web 2.0 Application development with Ruby on Rails

RIAA

Rich Internet application� web app with characteristics of desktop

applications

� using browser plugins like Flash

� Frameworks: Curl, Adobe Flash/Adobe

Flex/AIR, Java/JavaFX and Microsoft

Silverlight

Web 2.0 Application Development – p. 123

Page 124: Web 2.0 Application development with Ruby on Rails

Other latest trends

Keep an eye on these too� Offline Web apps

� Nosql - MongoDB, CouchDB, Tokyo cabinet

Web 2.0 Application Development – p. 124

Page 125: Web 2.0 Application development with Ruby on Rails

Thanks

Web 2.0 Application Development – p. 125