Upload
yucefmerhi
View
787
Download
2
Embed Size (px)
DESCRIPTION
Citation preview
Communications Lab :: Web
Lecture 3: Sinatra
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.
Today
• Sinatra, server-side programming• Web Services • Your Sinatra FTP folder• Routes• Parameters• Strings, Integers, If statements
Server-side language
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
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
Forms
Remember these?
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
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
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.
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
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
tmp/always_restart.txt
• Makes sure your service is always re-started after making a change
• You don't need to change this
/public
• Keep any public facing assets, such as images, stylesheets and javascript files
• Static files
App.rb
• Main application• This is the file we'll be working in and changing
require 'rubygems'require 'sinatra'
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.
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
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".
Redirect to route
get '/foo' do redirect to('/bar')end
• Use this to redirect from one route to another.
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!"
Blocks
get '/' do "Hello World!"end
All together, this is called a block.
HTTP Methods
• HTTP stands for "Hyper Text Transfer Protocol"• Takes the following main four requests:
o GETo POSTo PUTo DELETE
GET
get '/' do "Hello World!"end • "getting" a page• Get some information that was requested
POST
post '/' do "Hello World!"end
• "posting" TO a page• Create a new entry
PUT
put '/:id' do "Hello World!"end
• update an existing entry
DELETE
delete '/:id' do "Hello World!"end
• deleting an existing entry
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
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
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.
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
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.
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 = ""
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">'
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.
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>
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
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.
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],
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
Parameters
Including a parameter in a string and returning it to the page:
get '/cars/:name' do "I want a #{params[:name]}!" end
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
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>
params.inspect
get '/' do params.inspectend • params.inspect shows the key/value pairs of all the
parameters
• params[:key]=value
Integers
• Type of variables that represents whole numbers (no decimal points or fractions)
get '/' do integer_variable = 30end
If statements
if EXPRESSION # code that gets run if EXPRESSION is TRUEelse # code that gets run if EXPRESSION is FALSEend
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!
If statements
You don't need to always include the "else" block.
if (40 < 50) html = html + "That's true!"end
Comparing Strings
if (params[:text] == 'red') "You wrote red in the text input box."end
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"
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
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
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"/>
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
Requests in Developer Inspector
Arduino and Sinatra
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.
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