57
Communications Lab :: Web Lecture 3: Sinatra

Lecture 3 - Comm Lab: Web @ ITP

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Lecture 3 - Comm Lab: Web @ ITP

Communications Lab :: Web

Lecture 3: Sinatra

Page 2: Lecture 3 - Comm Lab: Web @ ITP

Announcements

• Late assignments policy: A total of three (3) free late days are allowed over the course of the semester; you may distribute these free late days however you like among the assignments. Once these 3 days are exhausted, 10 points will be taken off each late day.

• New group where you can post questions about assignments: [email protected].

• Office hours will now be moved to Thursdays 7pm-9pm.

• Assignment #2 is due today. Make sure you've sent the links to your files by email.  

Page 3: Lecture 3 - Comm Lab: Web @ ITP

Today

• Sinatra, server-side programming• Web Services • Your Sinatra FTP folder• Routes• Parameters• Strings, Integers, If statements

Page 4: Lecture 3 - Comm Lab: Web @ ITP

Server-side language

Page 5: Lecture 3 - Comm Lab: Web @ ITP

What is Sinatra?

• Sinatra is a DSL (Domain Specific Language) that is used to create web applications

• Named after Frank Sinatra, apparently for having• "so much class he deserves a web-framework named

after him".• Simple - create a fully functional web app in just

one file. No complicated set up procedures or configuration.

• Flexible - can be used to build anything from the smallest of microsites to a full-scale web application.

• Lightweight

Page 6: Lecture 3 - Comm Lab: Web @ ITP

What's a web service?

• Small units of code designed to handle a limited set of tasks.  

• It's an easy way to distribute information to a large number of users

• Listens to requests, and based on different parameters it provides a response 

• Makes remote information available

Page 7: Lecture 3 - Comm Lab: Web @ ITP

Forms

Remember these?

Page 8: Lecture 3 - Comm Lab: Web @ ITP

How does a web service work?

• The web service provider defines a format for requests for its service and the response the service will generate -- we do this in app.rb

• A computer makes a request for the web services across the network

• The web service performs some action, and sends the response back

Page 9: Lecture 3 - Comm Lab: Web @ ITP

Examples

• translating text from one language to another

• finding the best price for a product online • retrieving a stock quote

• saving a new item on a to do list  • putting up a new post on Twitter

Page 10: Lecture 3 - Comm Lab: Web @ ITP

More Examples

Google Maps    http://maps.googleapis.com/maps/api/service/output?parameters

...where service indicates the particular service requested and output indicates the response format.  

Page 11: Lecture 3 - Comm Lab: Web @ ITP

Your Sinatra Folder

  Open Cyberduck, let's take a look at the structure of your Sinatra folder. app.rbconfig.ru/public/tmp    /always_restart.txt

Page 12: Lecture 3 - Comm Lab: Web @ ITP

Config.ru

• Configurations to run your service• You don't need to ever change this

require File.dirname(__FILE__) + '/app.rb'

before do s = request.path_info s[/^\/~(\w)+(\d)+\/sinatra\/[^\/|?]+/i] = "" request.path_info = send

run Sinatra::Application

Page 13: Lecture 3 - Comm Lab: Web @ ITP

tmp/always_restart.txt

• Makes sure your service is always re-started after making a change

• You don't need to change this

Page 14: Lecture 3 - Comm Lab: Web @ ITP

/public

• Keep any public facing assets, such as images, stylesheets and javascript files

 • Static files

Page 15: Lecture 3 - Comm Lab: Web @ ITP

App.rb

• Main application• This is the file we'll be working in and changing

 require 'rubygems'require 'sinatra'

Page 16: Lecture 3 - Comm Lab: Web @ ITP

Routes

app.rb:        get '/' do    get '/get_rectangle' do • Routes are the backbone of your application

 • They are like a guide-map to how users will navigate

the actions you define for your application. 

Page 17: Lecture 3 - Comm Lab: Web @ ITP

Routes

The paths Sinatra is listening to: 1. / 

o This is the main path, the root url of the application

2. /get_rectangleo The route we used in our rectangle exampleo The name can be whatever we want

 

Page 18: Lecture 3 - Comm Lab: Web @ ITP

Routes

• Routes are matched in the order they are defined. The first route that matches the request is invoked.    

    get '/' do      "do this"      end 

  get '/' do    "do that"  end • In this case, you would see "do this".

Page 19: Lecture 3 - Comm Lab: Web @ ITP

Redirect to route

get '/foo' do    redirect to('/bar')end

• Use this to redirect from one route to another.

Page 20: Lecture 3 - Comm Lab: Web @ ITP

The Handler

get '/' do  "Hello World!"end 

What happens when the user visits the root url? • In this case, the user sees the message "Hello

world!"

Page 21: Lecture 3 - Comm Lab: Web @ ITP

Blocks

get '/' do  "Hello World!"end 

All together, this is called a block.

Page 22: Lecture 3 - Comm Lab: Web @ ITP

HTTP Methods

• HTTP stands for "Hyper Text Transfer Protocol"• Takes the following main four requests:

o GETo POSTo PUTo DELETE

Page 23: Lecture 3 - Comm Lab: Web @ ITP

GET

get '/' do  "Hello World!"end  • "getting" a page•  Get some information that was requested

Page 24: Lecture 3 - Comm Lab: Web @ ITP

POST

post '/' do  "Hello World!"end

• "posting" TO a page•  Create a new entry

Page 25: Lecture 3 - Comm Lab: Web @ ITP

PUT

put '/:id' do  "Hello World!"end

• update an existing entry

Page 26: Lecture 3 - Comm Lab: Web @ ITP

DELETE

delete '/:id' do  "Hello World!"end

• deleting an existing entry

Page 27: Lecture 3 - Comm Lab: Web @ ITP

Method Examples

get '/animals' do     # get a listing of all the animals at a farm end 

get '/animal/:id' do     # just get one animal end 

post '/animal' do     # create a new animal listing end 

Page 28: Lecture 3 - Comm Lab: Web @ ITP

Method Examples

put '/animal/:id' do     # HTTP PUT request method to update an existing animal entry end 

delete '/animal/:id' do     # HTTP DELETE request method to remove an animal who's been sold end

Page 29: Lecture 3 - Comm Lab: Web @ ITP

Remember

get '/' do  "Hello World"end

post '/' do  "Hello world"end     We can define two or more handlers for the same route (here ‘/’) – but give different blocks of code based on the method of the request.

Page 30: Lecture 3 - Comm Lab: Web @ ITP

Comments

    All lines that start with a hash (#) are comments and doesn't get read as code.

    Example:get '/animals' do     # get a listing of all the animals at a farm end 

Page 31: Lecture 3 - Comm Lab: Web @ ITP

Variables

    form = ""     This defines a variable named "form" and sets its value to an empty string.

    By using a variable, you can remember a value and reuse it later.

Page 32: Lecture 3 - Comm Lab: Web @ ITP

Strings

"Hello World!" • Strings are a series of text between double quotes

or single quotes.  • Strings are a type of variable

 • Strings can be empty:     form = ""

Page 33: Lecture 3 - Comm Lab: Web @ ITP

Strings

"Hello" + " world" = "Hello world"• You can add strings together.

 form = form + '<form action="get_rectangle" method="GET">' 

This is the same as: form += '<form action="get_rectangle" method="GET">' 

Page 34: Lecture 3 - Comm Lab: Web @ ITP

Strings

    form += '<form action="get_rectangle" method="GET">'    form += '<p><label>text:</label> <input type="text" name="text" /></p>'    form += '<p><label>x:</label> <input type="text" name="x" /></p>'    form += '<p><label>y:</label> <input type="text" name="y" /></p>'    form += '<p><label>color:</label> <input type="text" name="color" /></p>'    form += '<p><input type="submit" value="create" /></p>'    form += '</form>'

This adds the form HTML to the first String.

Page 35: Lecture 3 - Comm Lab: Web @ ITP

Strings

<form action="/~irs221/sinatra/example1/get_rectangle" method="GET">  <p><label>text:</label> <input type="text" name="text" /></p>  <p><label>x:</label> <input type="text" name="x" /></p>  <p><label>y:</label> <input type="text" name="y" /></p>  <p><label>color:</label> <input type="text" name="color" /></p>  <p><input type="submit" value="create" /></p></form>

Page 36: Lecture 3 - Comm Lab: Web @ ITP

HTML snippet

<<-HTML<form action="/~irs221/sinatra/example1/get_rectangle" method="GET">  <p><label>text:</label> <input type="text" name="text" /></p>  <p><label>x:</label> <input type="text" name="x" /></p>  <p><label>y:</label> <input type="text" name="y" /></p>  <p><label>color:</label> <input type="text" name="color" /></p>  <p><input type="submit" value="create" /></p></form>

HTML

   Everything between <<-HTML and HTML will get printed as HTML

Page 37: Lecture 3 - Comm Lab: Web @ ITP

Remember

• The last line in a block always get returned!

• Since the last line is the variable form, and form contains all the Strings with HTML added together, they will get returned.

Page 38: Lecture 3 - Comm Lab: Web @ ITP

Parameters and variables

get '/:task' do  task_variable = params[:task]end• ‘:task’ – this is a named parameter, identifiable by

the leading colon(‘:’).• Named parameters are values taken from the url

that are accessible through the ‘params’ hash• set a variable called ‘task_variable’ equal to the

value of params[:task],

Page 39: Lecture 3 - Comm Lab: Web @ ITP

Parameters

    Params contains all of the information that has been sent as parameters - either through a form or via the url    Route patterns may include named parameters, accessible via the params hash:

    get '/cars/:name' do         # matches "GET /cars/ford" and "GET /cars/volvo"         # params[:name] is 'ford' or 'volvo'         "I want a #{params[:name]}!"     end   

Page 40: Lecture 3 - Comm Lab: Web @ ITP

Parameters

Including a parameter in a string and returning it to the page:

get '/cars/:name' do         "I want a #{params[:name]}!" end  

Page 41: Lecture 3 - Comm Lab: Web @ ITP

Parameters

get '/get_rectangle' do    rectangle = ""

    # This will create a rectangle using in-line CSS    # Each of the values submitted in the form can be accessed by params[:name]    rectangle += '<p style="width: ' + params[:x] + '; '    rectangle += 'height: ' + params[:y] + '; '    rectangle += 'background-color: ' + params[:color] + '">'    rectangle += params[:text] + '</p>';

    # The last line always gets returned    rectangleend

Page 42: Lecture 3 - Comm Lab: Web @ ITP

Parameters

    rectangle += '<p style="width: ' + params[:x] + '; '    rectangle += 'height: ' + params[:y] + '; '    rectangle += 'background-color: ' + params[:color] + '">'    rectangle += params[:text] + '</p>';

    Will look like...        <p style="width: 123; height: 123; background-color: red">red</p>

Page 43: Lecture 3 - Comm Lab: Web @ ITP

params.inspect

get '/' do    params.inspectend  • params.inspect shows the key/value pairs of all the

parameters 

• params[:key]=value

Page 44: Lecture 3 - Comm Lab: Web @ ITP

Integers

• Type of variables that represents whole numbers (no decimal points or fractions)

get '/' do    integer_variable = 30end 

Page 45: Lecture 3 - Comm Lab: Web @ ITP

If statements

if EXPRESSION   # code that gets run if EXPRESSION is TRUEelse   # code that gets run if EXPRESSION is FALSEend

Page 46: Lecture 3 - Comm Lab: Web @ ITP

If statements

html = "40 is less than 50. " if (40 < 50)     html = html + "That's true!"else    html = html + "That's false!"end

• What is getting returned to our page?• Answer: 40 is less than 50. That's true!

Page 47: Lecture 3 - Comm Lab: Web @ ITP

If statements

You don't need to always include the "else" block.

if (40 < 50)     html = html + "That's true!"end

Page 48: Lecture 3 - Comm Lab: Web @ ITP

Comparing Strings

if (params[:text] == 'red')     "You wrote red in the text input box."end

Page 49: Lecture 3 - Comm Lab: Web @ ITP

Arrays

    main_courses = [ 'pancakes', 'waffles' ]    sides = [ 'potatoes', 'eggs', 'fruit salad' ]    beverages = [ 'orange juice', 'grapefruit juice', 'coffee']

To access these:    sides[0]       # this will return "potatoes"    beverages[1]       #this will return "grapefruit juice"

Page 50: Lecture 3 - Comm Lab: Web @ ITP

HTTP Status Codes

• 100-101 - Informational Status Codes• 200-206 - Successful Status Codes• 300-307 - Redirection Status Codes• 400-416 - Client Error Status Codes• 500-505 - Server Error Status Codes

 

Page 51: Lecture 3 - Comm Lab: Web @ ITP

404 Not Found Status Code

    It means the file was not found on the server. • bit.ly • github.com• http://brightkite.com/404• http://www.lightpostcreative.com/404

Page 52: Lecture 3 - Comm Lab: Web @ ITP

Add a stylesheet

• You can put static files in sinatra/example1/public• So, add your file to that folder on FTP

 • Link to the entire stylesheet like so:• <link rel="stylesheet" type="text/css"

href="/~irs221/sinatra/example1/public/styles.css"/>

Page 53: Lecture 3 - Comm Lab: Web @ ITP

Add a stylesheet

<<-HTML<!DOCTYPE html><html>  <head>        <meta charset=utf-8 />        <title>HTML Snippet</title>        <link rel="stylesheet" type="text/css" href="/~irs221/sinatra/example1/public/styles.css"/>  </head>  <body><form action="/~irs221/sinatra/example1/get_rectangle" method="GET">  <p><label>text:</label> <input type="text" name="text" /></p></form></body></html>HTML

Page 54: Lecture 3 - Comm Lab: Web @ ITP

Requests in Developer Inspector

Page 55: Lecture 3 - Comm Lab: Web @ ITP

Arduino and Sinatra

Page 56: Lecture 3 - Comm Lab: Web @ ITP

Exercises

1.Create a calculator for your food. Choose how many items you want to buy, and calculate the total price based on that.

2. Create a poll for your classmates. Display a different answer (message, image, etc) depending on what they pick.

3. The Monty Hall Exercise:• Make your own route in app.rb which displays a

form. • Hide a prize behind one of the choices in the form.• Depending on what the user picks in the form,

display whether they won or lost the prize.

Page 57: Lecture 3 - Comm Lab: Web @ ITP

Next week

• How to create more applications in Sinatra• Datamapper and Sinatra - we'll take a look at how to

store and retrieve data• Assignment #3 is due at the beginning of next class.

Get the assignment on ruxystaicut.com/itp