Internet Technologies

Transcription

Internet TechnologiesIoT, Ruby on Rails and REST95-733 Internet Technologies1

IoT: Jeff Jaffe from W3C Consider a person’s watch (as an IoT device)It will participate in IoT wearable applications (since it is worn).It will participate in IoT medical applications (as it takes one’s pulseand links into personal medical information).It will participate in IoT Smart Homes (used to control the home).It will contribute to IoT Smart Cities (as the municipal infrastructure relies on dataabout weather and traffic).It will be used in IoT Smart Factories (to track its usage and condition).But to participate across all silos, and for applications to be built whichleverage all silos requires common data models, metadata, and an interoperablelayered model.95-733 Internet Technologies2

IoT : Where might Rails fit ?microcontrollerDumb devicesWeb server(Rails, Java,TCP/IP rt devicesSee video at https://www.youtube.com/watch?v 4FtnvyH0qq43

Ruby on RailsMaterial for this presentation was taken fromSebesta (PWWW, course text) and “AgileWeb Development with Rails” by Ruby,Thomas and Hansson, third edition.95-733 Internet Technologies4

Notes on Ruby From Sebesta's"Programming The World Wide Web"Ø Designed in Japan by Yukihiro MatsumotoØØØØØØReleased in 1996Designed to replace Perl and PythonRails, a web application developmentframework , was written in and uses RubyRuby is general purpose but probably themost common use of Ruby is RailsRails was developed by David Heinemeierand released in 2004Basecamp (project management), GitHub(web-based Git repository) are written in RoR95-733 Internet Technologies5

General Notes on Ruby(1)Ø To get started install rbenv or RVM (Ruby Version Manager)Ø Use ri command line tool to browse documentation (e.g., riInteger).Ø Use rdoc to create documentation (like Javadoc)Ø Ruby is a pure object-oriented language.Ø All variables reference objects.Ø Every data value is an object.Ø References are typeless.Ø All that is ever assigned in an assignment statement is theaddress of an object.Ø The is no way to declare a variable.Ø A scalar variable that has not been assigned a value has thevalue nil.95-733 Internet Technologies6

General Notes on Ruby(2)Ø Three categories of data types - scalars,arrays and hashesØ Two categories of scalars - numerics andcharacter stringsØ Everything (even classes) is an object.Ø Numeric types inherit from the Numeric classØ Float and Integer inherit from NumericØ Fixnum (32 bits) and Bignum inherit fromIntegerØ All string literals are String objectsØ The null string may be denoted as " or as '’”.Ø The String class has over 75 methods95-733 Internet Technologies7

General Notes on Ruby(3)ØØØØØØØØØØØRuby gems: “There is a gem for that”.A ruby gem provides functionality.May run on its own. A stand alone program. Rails is a gem.May be included in your code with require:require ‘aws/s3’ # to access Amazon Simple Storage Servicerequire is the same as the c language’s include.How do you install a gem? From the command line enter:gem install GEM NAME (usually from http://rubygems.org)gem install railsgem install jquery-railsgem install geocoder95-733 Internet Technologies8

Interactive Environment irb miles 1000 1000 milesPerHour 100 100 "Going #{miles} miles at #{milesPerHour} MPH takes #{1/milesPerHour.to f*miles} hours" "Going 1000 miles at 100 MPH takes 10.0 hours"95-733 Internet Technologies9

More interactive Ruby irb miles 1000 1000 s "The number of miles is #{miles}" "The number of miles is 1000" s "The number of miles is 1000"95-733 Internet Technologies10

Non-Interactive RubySave as one.rb and run with ruby one.rba "hi"b aputs aputs bb "OK"puts aputs bOutput hihihiOK95-733 Internet Technologies11

References are Typelessa 4puts aa "hello"puts aOutput 4hello95-733 Internet Technologies12

C Style Escapesputs nologies95-733 Internet Technologies13

Converting Casea "This is mixed case."puts a.upcaseputs aputs a.upcase!puts aTHIS IS MIXED CASE.This is mixed case.THIS IS MIXED CASE.THIS IS MIXED CASE.95-733 Internet Technologies14

Testing Equality(1)b "Cool course" "Cool course" # same contentputs bb "Cool course".equal?("Cool course") #same objectputs bputs 7 7.0 # same valueputs 7.eql?(7.0) # same value and same typeOutput truefalsetruefalse95-733 Internet Technologies15

Testing Equality(2)a "Ruby is cool."b "Ruby is cool."c bif a bputs "Cool"elseputs "Oops"endif c.equal?(b)puts "Too cool"elseputs "Big Oops"endif c.equal?(a)puts "Way cool"elseputs "Major Oops"endWhat’s the output? ruby test.rbCoolToo coolMajor Oops95-733 Internet Technologies16

Reading The Keyboardputs "Who are you?"name gets #include entered newlinename.chomp! #remove the newlineputs "Hi " name ", nice meeting you."Interaction Who are you?MikeHi Mike, nice meeting you.95-733 Internet Technologies17

Reading Integers#to i returns 0 on strings that are not integersputs "Enter two integers on two lines and I'll add them"a gets.to ib gets.to iputs a bInteraction Enter two integers on two lines and I'll add them24695-733 Internet Technologies18

Conditions with ifa 5if a 4puts "Inside the if"a 2endputs "a " a.to s(10)Output Inside the ifa 295-733 Internet Technologies19

Conditions with unlessa 5unless a 4puts "Inside the if"a 2endputs "a " a.to s(10)Output Inside the ifa 295-733 Internet Technologies20

Conditions with if elsea 5if a 4puts "Inside the if"a 2elseputs "a " a.to s(10)endOutput a 595-733 Internet Technologies21

Conditions with if/elsif/elsea 5if a 4puts "Inside the if"a 2elsif a 9puts "Inside the elsif"elseputs "Inside else”endOutput Inside the elsif95-733 Internet Technologies22

Conditions with case/whena 5case awhen 4 thenputs "The value is 4"when 5puts "The value is 5"endOutput The value is 595-733 Internet Technologies23

Conditions withcase/when/elsea 2case awhen 4 thenputs "The value is 4"when 5puts "The value is 5"elseputs "OK"endOutput OK95-733 Internet Technologies24

Statement ModifiersSuppose the body of an if or while has a single statement.Then, you may code it as:puts "This is displayed" if 4 3j 0puts j 1 if j 0j j 1 while j 100puts j95-733 Internet TechnologiesThis is displayed110025

Case/When with Rangea 4case awhen 4 then# after a match we are doneputs "The value is 4"when (3.500)puts "The value is between 3 and 500"elseputs "OK"endOutput The value is 495-733 Internet Technologies26

Value of Case/When (1)year 2009leap casewhen year % 400 0 then truewhen year % 100 0 then falseelse year % 4 0endputs leapOutput false95-733 Internet Technologies27

Value of Case/When(2)year 2009puts casewhen year % 400 0 then truewhen year % 100 0 then falseelse year % 4 0endWhat’s the output?Output false95-733 Internet Technologies28

Whiletop 100now 1sum 0while now topsum sum nownow 1endputs sumOutput 505095-733 Internet Technologies29

Untilj 100until j 0j j-1endputs jOutput -195-733 Internet Technologies30

Arrays(1)a [1,2,3,4,5]puts a[4]x a[0]puts xa ["To","be","or","not","to","be"]j 0while j 6puts a[j]j j 1endOutput 51Tobeornottobe95-733 Internet Technologies31

Arrays(2)a [1,2,3,4,5]j 0while j 5a[j] 0j j 1endputs a[1]Output 095-733 Internet Technologies32

Arrays(3)somedays ["Friday","Saturday","Sunday","Monday"]puts somedays.empty?puts somedays.sortOutput falseFridayMondaySaturdaySunday95-733 Internet Technologies33

Arrays(4)a [5,4,3,2,1]a.sort!puts aWhat’s the output?1234595-733 Internet Technologies34

Arrays(5) Set Intersection &a [5,4,3,2,1]b [5,4,1,2]c a&bputs cWhat’s the output?542195-733 Internet Technologies35

Arrays(6) Implement a Stackx Array.newk 0while k 5x.push(k)k k 1endwhile !x.empty?()y x.popputs yendWhat’s the output?4321095-733 Internet Technologies36

Arrays and Ranges(1)# Create an array from a Ruby rangeOutput 1.71234567# Create rangea (1.7)puts a#create arrayb a.to aputs b95-733 Internet Technologies37

Arrays and Ranges(2)#Ranges are objects with methodsv 'aa'.'az'u v.to aputs vputs u95-733 Internet TechnologiesOutput aa.azaaabac::awaxayaz38

Arrays and Ranges(3)a 1.10;b 10.20puts aputs bc a.to a & b.to aputs cWhat is the output?1.1010.201095-733 Internet Technologies39

Hashes (1)# Hashes are associative arrays# Each data element is paired with a key# Arrays use small ints for indexing# Hashes use a hash function on a stringkids ages {"Robert" 16, "Cristina" 14, "Sarah" 12, "Grace" 8}puts kids agesOutput Sarah12Cristina14Grace8Robert1695-733 Internet Technologies40

Hashes(2) Indexingkids ages {"Robert" 16, "Cristina" 14, "Sarah" 12, "Grace" 8}puts kids ages["Cristina"]Output 1495-733 Internet Technologies41

Hashes(3) Adding & Deletingkids ages {"Robert" 16, "Cristina" 14, "Sarah" 12, "Grace" 8}kids ages["Daniel"] 15kids ages.delete("Cristina")puts kids agesOutput Daniel15Sarah12Grace8Robert1695-733 Internet Technologies42

Hashes (4) Taking The Keyskids ages {"Robert" 16, "Cristina" 14, "Sarah" 12, "Grace" 8}m kids ages.keyskids ages.clearputs kids agesputs mOutput SarahCristinaGraceRobert95-733 Internet Technologies43

Hashes (5)grade Hash.newgrade["Mike"] "A "grade["Sue"] "A-"puts grade["Mike"]What’s the output?A 95-733 Internet Technologies44

Hashes with Symbols(1) s {:u 3, :t 4, :xyz "Cristina" }puts s[:xyz]Cristina(2) A Ruby symbol is an instance of the Symbol class.(3) In Rails we will see. % link to("Edit", :controller ”editcontroller", :action "edit") % The first parameter is a label on the link and the second parameter isa hash.(4) The link to method checks if the symbol :controller maps to a value andif so, is able to find “editcontoller” . Same with :action.95-733 Internet Technologies45

Hashes and JSON (1)# This programs demonstrates how Ruby may be used to parse# JSON strings.# Ruby represents the JSON object as a hash.require 'net/http'require 'json'# Simple test example. Set up a string holding a JSON object.s '{"Pirates":{"CF" : "McCutchen","P" : "Bernett","RF" : "Clemente"}}'# Get a hash from the JSON object. Same parse as in Javascript.parsedData JSON.parse(s)95-733 Internet Technologies46

Hashes and JSON (2)# Displayprint parsedData["Pirates"] # returns a Ruby hashprint "\n"print parsedData["Pirates"]["P"] "\n" #Bernettprint parsedData["Pirates"]["RF"] "\n" #Clemente95-733 Internet Technologies47

Hashes and JSON (3)# Go out to the internet and collect some JSON from Northwindrequire 'net/http'require 'json'url /Products(2)? format json"# Make an HTTP request and place the result in jsonStrjsonStr Net::HTTP.get response(URI.parse(url))data jsonStr.bodyjsonHash JSON.parse(data)# See if the product is discontinuedif (jsonHash["Discontinued"])print jsonHash["ProductName"].to s " is a discontinued product"else95-733 Internet Technologiesprint jsonHash["ProductName"].to s" is an active product"end48

A Digression: Check outODataCheck out https://northwinddatabase.codeplex.comWhat will this query vc/Products(1)/Order Details/? format jsonWhat would you like to do with this data?GET, PUT, DELETE, POSTThe Northwind database is an Open Data Protocol (Odata)implementation.Odata is based on REST. What is REST?95-733 Internet Technologies49

Open Data Protocol URL’s taken seriously Service Document exposes /Northwind.svc/ metadata describes content (entity data Northwind.svc/ metadata Each collection is like an RDBMS ind.95-73395-733 InternetInternet Technologies5050svc/Customers

Open Data Protocol .svc/Products(1)/? format json95-73395-733 InternetInternet Technologies5151

The OData API is RESTful Representational State Transfer (REST) Roy Fielding’s doctoral dissertation (2000) Fielding (along with Tim Berners-Lee)designed HTTP and URI’s. The question he tried to answer in his thesiswas “Why is the web so viral”? What is itsarchitecture? What are its principles? REST is an architectural style – guidelines,best practices.95-733 Internet TechnologiesNotes from “Restful Java withJAX-RS, Bill Burke, Orielly5252

REST Architectural Principles The web has addressable resources.Each resource has a URI. The web has a uniform and constrained interface.HTTP, for example, has a small number ofmethods. Use these to manipulate resources. The web is representation oriented – providingdiverse formats. The web may be used to communicate statelessly– providing scalability Hypermedia is used as the engine of applicationstate.95-733 Internet Technologies5353

Back to Ruby: Methods# Methods may be defined outside classes# to form functions or within classes to# form methods. Methods must begin with lower case# letters.# If no parameters then parentheses are omitted.def testMethodreturn Time.nowenddef testMethod2Time.nowendputs testMethodputs testMethod2Output Tue Feb 10 22:12:44 -0500 2009Tue Feb 10 22:12:44 -0500 200995-733 Internet Technologies54

Methods Local Variablesdef looperi 0while i 5puts ii i 1endendlooperWhat’s the output?Output 0123495-733 Internet Technologies55

Scalers Are Pass By Value#scalers are pass by valuedef looper(n)i 0while i nputs ii i 1endendOutput 012looper(3)95-733 Internet Technologies56

Parenthesis Are Optional#scalers are pass by valuedef looper(n)i 0while i nputs ii i 1endendOutput 012looper 395-733 Internet Technologies57

Passing Code Blocks (1)def looper(n)i 0while i nyield ii i 1endendlooper (3) do x puts x endlooper (4) { x puts x }Output 012012395-733 Internet TechnologiesThink of the codeblock as a methodwith no name.Only one code blockmay be passed.Use procs orlambdas if youneed more.58

Passing Code Blocks (2)def looperi 0n 4while i nyield ii i 1endendValueValueValueValuelooper{ x puts "Value #{x}" }95-733 Internet Technologies0123Think of the codeblock as a methodwith no name.59

Passing Code Blocks (3)def interest(balance)yield balanceendWhat’s the output?interest is 150.0interest is 1120.0rate 0.15interestAmt interest(1000.0) { bal bal * rate }print "interest is #{interestAmt}"rate 0.12total interest(1000.0) { bal bal * (rate 1.0)}print "interest is #{total}"95-733 Internet Technologies60

Passing Code Blocks (4)Many Ruby methods take blocks.[1,2,3,4,5].each { x puts "Doubled #{x*2}"}DoubledDoubledDoubledDoubledDoubled95-733 Internet Technologies 2 4 6 8 1061

Passing Code Blocks (5)Many Ruby methods take blocks.Collect returns an array. What’s the output?t [1,2,3,4,5].collect { x x*2}puts tt [1,2,3,4,5].collect do x x 1 endputs t95-733 Internet Technologies2468102345662

Passing Code Blocks (6)XML Processing and XPATH predicates.# We want to read the schedule for this class.# For command line processing use ARGV[0] rather than hard coding the name.require "rexml/document” # Ruby Electric XML comes with standard distributionfile File.new( "schedule.xml" )doc es/Topic[. 'Ruby and Ruby On Rails']”) { element puts element } Topic Ruby and Ruby On Rails /Topic 95-733 Internet Technologies63

Or Remotelyrequire "rexml/document"require 'open-uri'remoteFile hedule.xml') { f f.read }doc //Slides/Topic[. 'Ruby and Ruby On Rails']") { e puts e }95-733 Internet Technologies64

Passing Code Blocks(7)# integers are objects with methods that take code blocks.4.times {puts "Yo!"}Output Yo!Yo!Yo!Yo!95-733 Internet Technologies65

Arrays and Hashes Are PassBy Referencedef coolsorter(n)n.sort!endn [5,4,3,2,1]coolsorter(n)puts nWhat’s the output?Output 1234595-733 Internet Technologies66

Classes# Classes and constants must begin with# an uppercase character.# Instance variable begin with an "@" sign.# The constructor is named initializeclass Studentdef initialize(n 5)@course Array.new(n)enddef getCourse(i)return @course[i]enddef setCourse(c,i)@course[i] cendendindividual Student.new(3)individual.setCourse("Chemistry", 0)puts individual.getCourse(0)Output Chemistry95-733 Internet Technologies67

Simple Inheritanceclass Mammaldef breatheputs "inhale and exhale"endendclass Cat Mammaldef speakputs "Meow"endendclass Dog Mammaldef speakputs "Woof"endendpeanut Dog.newsam Cat.newpeanut.speaksam.speaksam.breatheOutput WoofMeowinhale and exhaleRuby has no multiple inheritance.95-733 Internet Technologies68

Self makes a method a classmethod. @@ is a class variable.class Mammal@@total 0def initialize@@total @@total 1enddef breatheputs "inhale and exhale"enddef self.total createdreturn @@totalendendclass Cat Mammaldef speakputs "Meow"endendclass Dog Mammaldef speakputs "Woof"endendpeanut Dog.newsam ale and exhale2puts Mammal.total created95-733 Internet Technologies69

Public, Private and Protectedclass Mammaldef breathe # method is publicputs "inhale and exhale"endprotecteddef move# method available to inheritorsputs "wiggle wiggle"endprivatedef sleep# private methodputs "quiet please"endend95-733 Internet Technologiesclass Cat Mammaldef speakmoveputs "Meow"endendclass Dog Mammaldef speakmoveputs "Woof"endendpeanut Dog.newsam Cat.newpeanut.speaksam.speaksam.breathe70

Duck Typingclass Duckdef quackputs "Quaaaaaack!"enddef feathersputs "The duck has white and gray feathers."endendclass Persondef quackputs "The person imitates a duck."end95-733 Internet TechnologiesFrom Wikipedia71

Duck Typing (2)def feathersputs "The person takes a feather from the ground and shows it."endenddef in the forest duckduck.quackduck.feathersend# takes anything that quacks with feathersFrom Wikipedia95-733 Internet Technologies72

Duck Typing (3)def gamedonald Duck.newjohn Person.newin the forest donaldin the forest johnendgameFrom Wikipedia95-733 Internet Technologies73

Reflectionclass Dogdef barkputs "woof woof"enddef furputs "This dog likes you to pat her fur."endendscout Dog.newif(scout.respond to?("name"))puts "She responds to name"endif(scout.respond to?("bark"))puts "She responds to bark"puts scout.barkend95-733 Internet TechnologiesShe responds to barkwoof woof74

ModulesModules group together methods and constants.A module has no instances or subclasses.To call a module’s method, use the module name,followed by a dot, followed by the name of the method.To use a module’s constant, use the module name,followed by two colons and the name of the constant.Think “namespace”.95-733 Internet Technologies75

Modulesmodule StudentMAXCLASSSIZE 105class GradStudentdef workputs "think, present, present,."ruby onemodule.rbendthink, present, present,.def eatputs "pizza"enddef sleepInclude this module withputs "zzzzz"require. Similar to Java’sendendimport or C’s #include.endx 6mike Student::GradStudent.newmike.work if x Student::MAXCLASSSIZE95-733 Internet Technologies76

Mixinsmodule SomeCoolMethodsThe methods of amodule become membersof a class. Think “multipleinheritance” in Ruby.def fooputs "foo is running"enddef foo2puts "foo2 is running"endIf this were an externalmodule it would be ‘required’first. Then ‘included’.endclass CoolClassinclude SomeCoolMethodsendx CoolClass.newx.foo2‘require’ is like C’s include.‘include’ is used for mixins.95-733 Internet Technologies77

Ruby Supports ClosuresA closure is a first class function with free variablesthat are bound in the lexical environment.(From Wikipedia)Put another way: A closure is a method with twoproperties:1.It can be passed around and can be called at a latertime and2. It has access to variables that were in scope at thetime the method was created.From: Alan Skorkin’s “Closures – A simple explanation95-733 Internet Technologies78

Javascript has Closures Too!function foo(x) {return function() { alert("Hi " x); }}var t foo("Mike");var m foo("Sue");t();m();79

Javascript has Closures Too! html head script type "text/javascript” // define printMessage to point to a functionvar printMessage function (s) {alert("In printMessage() for " s)var f function () {alert(s ' was pressed.');}return f;}// call function pointed to be printMessage// with a parameter.// A pointer to a function is returned.// The inner function has a copy of s.buttonA printMessage('A')buttonB printMessage("B")buttonC printMessage("C”)80

Closures in Javascript /script title Closure example /title /head body !-- call the function pointed to by the variable -- button type "button" onClick "buttonA()" A Button Click Me! /button button type "button" onClick "buttonB()" B Button Click Me! /button button type "button" onClick "buttonC()" C Button Click Me! /button /body /html What’s the output?95-733 Internet Technologies81

Closures in JavascriptOn page load:In printMessage() for AIn printMessage() for BIn printMessage() for CThree buttons appearClick A “A was pressed”Click B “B was pressed”95-733 Internet Technologies82

A Closure in Rubydef foo (p)p.callend#call the procx 24#create a proc to passp Proc.new { puts x }foo(p)x 19foo(p)Quiz: What’s the output?95-733 Internet TechnologiesNote: It is easy topass two or moreprocs. Only onecode block may bepassed.Note: x is notwithin the scopeof foo.Note: a referenceto x is used. Not83a value.

A Closure in Rubydef foo (p)p.callend#call the procx 24#create a proc to passp Proc.new { puts x }2419foo(p)x 19foo(p)95-733 Internet Technologies84

Another Ruby Closureclass ACoolClassdef initialize(value1)@value1 value1enddef set(i)@value1 ienddef display(value2)lambda { puts "Value1: #{@value1}, Value2: #{value2}"}endenddef caller(some closure)some closure.callendobj1 ACoolClass.new(5)p obj1.display("some values")caller(p)p.call()obj1.set(3)95-733 Internet Technologiesp.callLambdas areprocs butwith arity checkingand different returnsemantics.Quiz: What’s theoutput?85

Another Ruby Closure (2)class ACoolClassdef initialize(value1)@value1 value1enddef set(i)@value1 ienddef display(value2)lambda { puts "Value1: #{@value1}, Value2: #{value2}"}endenddef caller(some closure)ruby closure.rbsome closure.callValue1: 5, Value2:endobj1 ACoolClass.new(5)Value1: 5, Value2:p obj1.display("some values")Value1: 3, Value2:caller(p)p.call()obj1.set(3)95-733 Internet Technologiesp.callsome valuessome valuessome values86

Pattern Matching#Pattern matching using regular expressionsline "http://www.andrew.cmu.edu"loc line /www/puts "www is at position #{loc}"Output www is at position 795-733 Internet Technologies87

Regular Expressions# This split is based on a space, period or comma followed# by zero or more whitespace.line2 "www.cmu.edu is where it's at."arr line2.split(/[ .,]\s*/)puts arr95-733 Internet TechnologiesOutput wwwcmueduiswhereit'sat88

Passing Hashesdef foo(a,hash)hash.each pair do key, val puts "#{key} - #{val}"endendfoo("Hello",{:cool "Value", :tooCool "anotherValue" })# Or, we may drop the parens foo "Hello" ,{:cool "Value", :tooCool "anotherValue" }95-733 Internet Technologies89

Ruby On Rails(1)“A framework is a system in which much of the more orless standard parts are furnished by the framework, sothat they do not need to be written by the applicationdeveloper.” Source: SebestaLike Tapestry and Struts, Rails is based on the Model ViewController architecture for applications.MVC developed at XeroxPARC by the Smalltalk group.95-733 Internet Technologies90

Ruby On Rails (2) Two fundamental principles:-- DRY (Don’t Repeat Yourself)-- Convention over configuration Rails is a product of a software development paradigmcalled agile development. Part of being agile is quick development of workingsoftware rather than the creation of elaboratedocumentation and then software.95-733 Internet Technologies91

Model View Controller The Model is the data and any enforced constraints onthe data. Rails uses Object Relationship Mapping.A class corresponds to a table. An object correspondsto a row. The View prepares and presents results to the user. The Controller performs required computations andcontrols the application.Source: Sebesta95-733 Internet Technologies92

Model View Controller§ Rails is a web-application and persistence framework.§ MVC splits the view into "dumb" templates that areprimarily responsible for inserting pre-built data inbetween HTML tags.§ The model contains the "smart" domain objects (suchas Account, Product, Person.§ The model holds all the business logic and knows how topersist itself to a database.§ The controller handles the incoming requests (such asSave New Account, Update Product, Show Person)by manipulating the model and directing data to the view.From the Rails README95-733 Internet Technologies93

Model View Controllerbrowser§controllerviewmodel95-733 Internet TechnologiesRDBMS94

Routerbrowser§Recognizes URL’s andchooses the controller andmethod to execute.controllerActionPackDynamic contentapproaches:view-ERB-XML Builder-RJS for Record95-733 Internet Technologies95

Rails Tools§ Rails provides command line tools.The following command creates many directoriesand subdirectories including models, views, andcontrollers: rails new greet cd greet rails generate controller sayAdd get ‘/say/hello’, to: ‘say#hello’ to the endof greet/config/routes.rbOr, add get '/say/hello', :to 'say#hello'Add an HTML file named hello.html.erb togreet/app/views/say rails server95-733 Internet Technologies96

Rails Directoriesgreetappcontrollerssay controller.rbviewssayclass SayController ApplicationControllerdef hellosay controllerhello method in controllerhello.html.erb95-733 Internet Technologies97

hello.html.erbviewssayhello.html.erb html !– all instance variables of thecontroller are visible here. - - body b Ruby says "Yo Mike". /b %a 32% Ruby is % a% degrees cool. /body /html 95-733 Internet Technologies98

Two Examples From Sebesta Hello world application Processing a Popcorn Form95-733 Internet Technologies99

Using NetbeansSee Tom Enebo’s NetBeans Ruby Project95-733 Internet Technologies100

Create an RoR Project95-733 Internet Technologies101

Select MySQL95-733 Internet Technologies102

Models Views and Controllers95-733 Internet Technologies103

Run And Visit Rails95-733 Internet Technologies104

Generate A Controller95-733 Internet Technologies105

Modify The Default Controller# The program say controller.rb is the specific controller# for the SebestaProject1 project.# Add the definition of the hello method.class SayController ApplicationControllerdef helloendend“hello” becomes part of the URL andtells the controller about the view.95-733 Internet Technologies106

Enter The View1.2.3.4.Select SebestaProject1/Views/SayRight ClickNew HTML fileFile name hello.html.erb html !– all instance variables of the controller are visible here. - - body b Ruby says "Yo Mike". /b %a 32% Ruby is % a% degrees cool. /body /html 95-733 Internet Technologies107

Run And Visit The ApplicationAs an exercise, include the helper call % link to "Cool", :action "hello" % in the html.95-733 Internet TechnologiesSo far, no model.108

Processing Forms95-733 Internet Technologies109

Result95-733 Internet Technologies110

routes.rbget '/home/the form', to: 'home#the form'post '/home/result', to: 'home#result'Quiz: How could these routes be written with :to ratherthan to: ?95-733 Internet Technologies111

The Home controller(1)class HomeController ApplicationControllerdef the formend95-733 Internet Technologies112

The Home controller(2)def result@name params[:name]@street params[:street]@city params[:city]@unpop params[:unpop].to i@unpop cost 3.0 * @unpop@caramel params[:caramel].to i@caramel cost @caramel * 3.5@unpop cost sprintf("%5.2f",@unpop cost)@caramel cost sprintf("%5.2f",@caramel cost)endend95-733 Internet Technologies113

The Form View(1) % form tag("/home/result", method: "post") do % table tr td % label tag(:name, "Buyer's Name:") % /td td % text field tag(:name) % /td /tr tr td % label tag(:street, "Street Address:") % /td td % text field tag(:street) % /td /tr 95-733 Internet Technologies114

The Form View(2) tr td % label tag(:city, "City, State, Zip:") % /td td % text field tag(:city) % /td /tr /table table border "border" tr th Product Name /th th Price /th th Quantity /th /tr 95-733 Internet Technologies115

The Form View(3)the form.html.erb tr td 3.00 /td td % label tag(:unpop, "Unpopped Corn 1 LB") % /td td % text field tag(:unpop) % /td /tr tr td 3.50 /td td % label tag(:caramel, "Caramel Corn 2 LB") % /td td % text field tag(:caramel) % /td /tr /table % submit tag("Submit Data") % % end % 95-733 Internet Technologies116

Results View(result.html.erb)(1) h4 Customer: /h4 % @name % br/ % @street % br/ % @city % p/ p/ 95-733 Internet Technologies117

Ø Rails, a web application development framework , was written in and uses Ruby Ø Ruby is general purpose but probably the most common use of Ruby is Rails Ø Rails was developed by David Heinemeier and released in 2004 Ø Basecamp (project management), GitHub (