Advanced Web Programming
Mr. Prashant Ankalkoti
Asst.Prof, Dept. Of MCA
J N N C E, Shivamogga.
Email :
[email protected] Mob : 9886363246 1
Origins and Uses of Ruby
▪ Developed by Yukihiro Matsumoto about 1996
▪ Purely interpreted
– Somewhat easier learning because of simple structure
▪ Notable characteristics
– Regular expressions based on Perl
– Dynamic classes based on JavaScript
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Scalar Types and Their Operations
▪ Three categories of data
– Scalars
– Arrays
– Hashes
▪ All values are objects, including numeric values
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Numeric Literals
▪ Numeric data are descendants of class Numeric
– Float and Integer
– Fixnum and Bignum
▪ Integer literals are Fixnum unless too large, then Bignum
▪ Underscores can punctuate integer literals
▪ Float literals may not have a decimal point first or last
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
String Literals
▪ Single or double quoted
– Double quoted has escape characters and expression interpolation
▪ Expression is specified by #{…}
– Single quoted have not escape characters or expression
interpolation
▪ q$...$ for a single quoted string
– $ can be other characters
– <{([ as the start delimiter must be matched by >})] at the end
▪ Q$...$ for a double quoted string
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Variables and Assignment Statements
▪ Variable names indicate category of variables
▪ Variables are not formally declared and do not have a fixed type
▪ An identifier begins with a lower case letter or underscore followed by
letters and/or digits and/or underscore
▪ Variables are all references to objects
▪ An unassigned variable has value nil
▪ Named constants are named like variables but have names that begin with
a capital letter
▪ There are some implicit variables such as $_
▪ Assignment statements in Ruby are the same as in the C/C++/Java family
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Numeric Operators
▪ Standard operators: + - * / %
– Integer/Integer is integer
▪ ** for exponentiation
▪ Missing: ++ and –
▪ Math module: cos, sin, log, sqrt, …
▪ The interactive Ruby interpreter irb takes experssions and
responds with the values
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
String Methods
▪ Catenation is indicated by +
▪ << appends its right operand to the left
– Similar to an assignment operator
– += is a synonym
▪ capitalize, chop, chomp, upcase, …
– These create new strings
▪ Mutator versions capialize!, chop!, chomp!, upcase! modify
the string
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
String Character Access
▪ [ index ]
– Single character reference returns the ASCII code of a character
▪ [index]=
▪ [first-char, numer-of-chars] gets a substring
▪ [first-char, numer-of-chars]= replaces a substring
▪ == compares strings for equality based on content
– equal? compares for the same object
– eql? compares for type and value
▪ <=> compares two strings returning -1 if the first is smaller, 0 if they are
equal, +1 if the second is smaller
▪ * is used to repeat a string: “x” * 3 is “xxx”
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 10
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 11
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 12
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 13
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 14
Screen Output
▪ Operator puts displays a string on standard output
– A new line is added to the output
▪ Operator print displays a string without the new line
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Keyboard Input
▪ Function gets gets a line of input from the console (keyboard)
▪ gets.chomp returns the next lline of input with out the
terminating new line
▪ gets.to_i returns the next line of input converted to an
integer
▪ gets.to_f returns the next line of input converted to a float
▪ Example quadeval.rb illustrates console input and output
– Run with the command
ruby quadeval.rb
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 17
Control Expressions
▪ A Boolean expression
▪ Any value but nil is considered true
▪ Comparison operators
– Usual: == != < > <= >=
– Compare for order: <=>
– Compare for type and value: eql?
– Compare for equality of object: equal?
▪ Operator precedence and associativity
▪ Assignments can be used as control expressions
next = gets
– This is true as long a there is more input
– Becomes false when input is exhausted
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 19
Selection and Loop Statements
▪ If statement
if control-expression
statements
elsif control-expression
statements
else
statements
end
▪ elsif can be repeated any number of times (including 0)
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 21
Unless
▪ Reverses if, no else or elsif
unless control-expression
statements
end
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 23
Case Syntax
case expression
when value then
- statement sequence
when value then
- statement sequence
[else
- statement sequence]
end
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Case Semantics
▪ Value is matched to when’s using ===
– Defined for all built-in classes
– If the when value is a class, the comparison is true if the case value is an
object of the class or one of its super classes
– If the value is a range, the case value matches if it is in that range
– If the when value is a regular expression, the match is based on pattern
matching
▪ When’s do not cascade, so no break statements are needed
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Case Expression
▪ Syntax
case
when Boolean expression then expression
...
when Boolean expression then expression
else expression
end
▪ The first true Boolean expression causes the matching expression to
be evaluated as the value of the case
– The else expression is used if none of the Booleans are true
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 27
Loops
▪ While loop repeats while control expression is true
▪ Until loop repeats until control expression is true
▪ loop introduces an infinite loop
– A code block is a sequence of statements delimited by braces or by
keywords begin and end
– The loop keyword is followed by a code block
– Exit from the loop is by the break statement
– The next statement causes control to go back to the beginning of the code
block
▪ Iterator methods are an important repetition construct in Ruby
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 29
Fundamentals of Arrays
▪ Ruby arrays are dynamic in size and can store different types of
data in different elements
▪ Creating an array
– Array.new(size)
– Array.new(size, value)
– A literal list such as [2, 4, 6]
▪ Element access through subscript [sub]
▪ Element assignment through [sub]=
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
▪ Example: >>list1=Array.new(5)
>> [nil, nil, nil, nil, nil]
Second, to assign a list literal to a variable.
Example: >>list2=[2,4,6,”jnnce”,2]
>> [2,4,6,”jnnce”,2]
Example: >>list3=Array.new(3,”jnnce”)
>> [“jnnce”,”jnnce”,”jnnce”]
The length of an array can be retrieved with the length method.
Example: >>list3.length
>> 3
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 31
All ruby array elements use integers as subscripts, and the lower bound
subscript of every array is zero.
Example: >> ruby = [2,4,6,8,9]
>> [2,4,6,8,9]
>> ada = ruby[2]
>> 6
>> ruby[3] = 10
>> 10
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 32
The for-in Statement
▪ Syntax
for variable in list
statements
end
▪ The variable takes on each value in the
list
– This is not a reference but a value copy
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Build-In Methods for Arrays and Lists
▪ push inserts at the end of a list
▪ pop removes from the end of a list and returns the value
▪ unshift inserts at the beginning of a list
▪ shift removes from the front of a list and returns the value
▪ Arrays catenated with +
▪ Method reverse returns a reversed copy
▪ Method reverse! reverses the array
▪ include? searches an array
▪ sort sorts an array, returns a new array
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
An Example
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
36
▪ concat:
If an array is to be catenated to the end of another array, concat is used.
Example: >> mca1 = [1,2,3]
=> [1, 2, 3]
>> mca2 = [6,8,7]
=> [6, 8, 7]
>> mca1.concat(mca2)
=> [1, 2, 3, 6, 8, 7]
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 37
• reverse: The reverse method does what its name implies.
Example: >> rns2
=> [6, 8, 7]
>> rns2.reverse
=> [7, 8, 6]
• include?: The include? predicate method searches an array for a specific object.
Example: >> rns2
=> [6, 8, 7]
>> rns2.include?(6)
=> true
• sort: The sort method sorts the elements of an array.
Example: >> rns3 = [90,54,23,12]
=> [90, 54, 23, 12]
>> rns3.sort
=> [12, 23, 54, 90]
38
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 39
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 40
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 41
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 42
Example: >> jnnce={"mca"=>12,"mba"=>10,"puc"=>6}
=> {"mca"=>12, "mba"=>10, "puc"=>6}
>> jnnce.keys
=> ["mca", "mba", "puc"]
>> jnnce.values
=> [12, 10, 6]
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 43
Methods
▪ Methods can be defined outside classes
▪ When a method is called without an object reference, the default
is self
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Fundamentals of Methods
▪ Method syntax
def name [( formal-parameters )]
statements
end
– Parentheses can be omitted if there are no formal parameters
▪ Return statement ends execution of the method
– With a value, it returns the value as the value of the method
– If no return ends a method, the last expression is the value of the method
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 46
Local Variables
▪ Variables used in a method are local to the method.
▪ Global variables with the same name are hidden.
▪ Local variable names must begin with a lowercase letter or an
underscore.
▪ The lifetime of a local variable from its creation to the end of the
execution of the method.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 48
Parameters
▪ Parameters are passed by value unless arrays and hashes
– Arrays and hashes are passed by reference
▪ The number of actual parameters must match the number of formal
parameters
– If the last formal parameter is preceded by an asterisk, it receives all actual
parameters not matched to earlier formal parameters
▪ Formal parameters can be assigned default values, so the corresponding
actual parameter may be omitted
▪ If a hash literal is the last actual parameter, the curly braces are not
required
– In this case symbols are conventionally used as the keys
– A symbol is an unquoted string preceded by a colon
▪ Example method median computes the median of an array parameter
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 50
Basics of Classes
▪ Syntax
class class-name
…
end
▪ Class names begin with an uppercase letter
▪ Instance variables have instances for each object
– Names begin with @
▪ Constructor is named initialize
▪ Members can by dynamically added and removed from a class
– Method remove_method removes a method
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 52
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 53
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 54
Access Control
▪ Three levels
– Public: every method has access
– Private: only methods of the object have access
▪ Private methods may not be invoked with an object reference, so must default to self
▪ Different from C++ and Java
– Protected: only methods of the class or subclasses have access
▪ Instance data is private and that cannot be changed
▪ Access control methods change access level
– Invoked without parameters change the default for following methods
– Invoked with parameters, these are symbols naming methods that have
access changed
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 56
Attributes
▪ Method attr_reader takes symbol arguments and
defines get methods named after the symbols
attr_reader :val
– Defines a method named val that returns the value of @val
▪ Method attr_writer takes symbol arguments and
defines an assignment method
attr_writer :val
– Defines a method named val= that allows assignment to the
attribute as in
obj.val = 17;
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
▪ attr_accessor :var
▪ attr_reader :var
▪ attr_writer :var
▪ Well, attr_accessor creates both the READER & WRITER
methods.
▪ attr_reader creates only the reader.
▪ attr_writer creates only the writer.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 58
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 59
Inheritance
▪ Syntax
class My_Subclass < Base_class
▪ Access level of a method can be changed in a subclass
– A method can be made private and, thus, inaccessible through
that subclass
▪ Modules define namespaces that are often used to hold sets of
methods
▪ Modules may be mixed in to classes, providing methods to the class
by a non-inheritance route
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 61
Code Blocks and Iterators
▪ A code block is a sequence of statements delimited by braces or
by do/end
– A code block can have parameters, listed at the beginning of the block,
surrounded by vertical bars: |a, b|
▪ A code block may be passed to a method call, following the actual
parameters of the call
▪ In the method body, a call to yield will executed the block
– Actual parameters of the call are matched with the block parameters
▪ An iterator applies a block to the values in a list
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Built-in Iterators
▪ each is a method of arrays and takes a block that has one parameter
– The block is executed with the block parameter taking each element of the
list in turn
▪ The upto method applies to integers and takes an integer parameter
and a block with one parameter
– The block is executed for each value in the range from the target integer to
the actual parameter, inclusive
▪ The collect method creates an array from the results of applying a
block to each element in an array
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
64
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 65
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 66
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 67
Pattern Matching
▪ Pattern matching in Ruby is based on pattern matching in
Perl
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Basics of Pattern Matching
▪ Patterns are delimited by slashes
▪ =~ is the pattern matching operator
▪ The split method is used to split a string with separators given
by a regular expression
– A hash is used to count word frequencies
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Remembering Matches
▪ Parts of a regular expression pattern can be enclosed in
parentheses
▪ If there is a match, the variables $1, $2 … hold the strings
matched by the parenthesized parts
▪ If there is a match, $`, $& and $’ hold the part of the target before
the match, the part matched and the part after the match
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 71
Substitutions
▪ Method sub substitutes its second parameter for the first
match found of the first parameter
▪ Method gsub is similar but substitutes for all matches
▪ Both methods create new strings
▪ sub! and gsub! change the target string
▪ The i modifier on a pattern causes the match to ignore
letter case
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
▪ Example: >> str = "we belongs to jnnce family. jnnce"
▪ => "we belongs to jnnce family. jnnce"
▪ >> str.sub(/jnnce/,“jnn")
▪ => "we belongs to jnn family. jnnce"
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 73
▪ gsub method
▪ The gsub method is similar to sub, but finds all substring
matches and replaces all of them with its second parameter.
▪ Example: >> str
▪ => "we belongs to jnnce family. jnnce"
▪ >> str.gsub (/jnnce/,“jnn")
▪ => "we belongs to jnn family. jnn"
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 74
▪ i modifier
▪ The i modifier, which tells the pattern matcher to ignore the case
of letters.
▪ Example: >> strg = "Is it Rose, rose, or ROSE?"
▪ => "Is it Rose, rose, or ROSE?"
▪ >> strg.gsub(/Rose/i, "rose")
▪ => "Is it rose, rose, or rose?"
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 75
Overview of Rails
▪ Rails is Ruby based
▪ “A development framework for Web-based applications”
▪ Rails uses the Model-View-Controller architecture
– Model classes are the data classes, including constraint enforcement
– View classes present the data to the user
– Controller classes perform computations and deal with user interaction
▪ Rails uses an Object-Relational Mapping approach to working with databases
– A cars table corresponds to a car class
– The rows of the table correspond to instances of the class
– The correspondence is built automatically by the Rails framework
▪ Rails uses a combination of Ruby code and template files to create responses
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 77
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 78
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 79
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 80
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 81
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 82
Developer Tasks
▪ Design and build the model, including a database for storing model
data
▪ Design and implement actions
▪ Design and implement the views
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Document requests
▪ The Rails framework provides much of the superstructure
necessary for a web application
▪ Scripts with the Rails framework set up the basic structure
▪ The first Rails example serves a single static document
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 85
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 86
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 87
Project Setup
▪ The Instant Rails package provides all the components needed to develop and test Rails
projects on a Microsoft Windows platform
▪ Start the InstantRails console
InstantRails
▪ Set up a rails application
rails rails1
▪ Generate a controller
ruby script/generate controller say
▪ Run the default server
ruby script/server
– The server runs for a particular application
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Project Directory Structure
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Project Components
▪ A controller class, SayController, in the controllers
directory
▪ The controller class has method named hello
▪ An html template file (static for this example) named
hello.rhtml in directory views\say
▪ The Rails framework associates these components by the name
‘say’
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Request Processing
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Dynamic Documents
▪ The next example displays the greeting but also displays the
current time
– Uses Time.now from the Ruby library
▪ <% … %> embeds Ruby code in template files
– <%= … %> causes the value of the executed code to be inserted in place
▪ Instance variables of the controller class can be accessed in the
template file
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 93
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 94
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 95
Processing Forms
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Setting Up the Applications
▪ A controller home is created
▪ An empty action method the_form is created
▪ A static template file the_form.rhtml is created to display the
initial data entry form
▪ The action on the form is simply “result” which links to an action
method named result in the same controller class
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
The Controller and the View
▪ Action method result in the controller class
– Get form data
– Compute results
▪ Object params holds the form data in a hash-like object
– Can be indexed by symbols or by strings using widget names
– params[:phone] gets the phone number
– params[:unpop].to_i gets the unpopped amount as an integer
▪ The sprintf method can be used to format data
– Used with format specification %5.2d to format floating numbers with exactly
two decimal places
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 99
Rails Applications with Databases
▪ This example uses the Corvettes database
▪ The user specifies model year limits and body styles
▪ The response is a list of matching cars
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Building the Database
▪ A database is created with four tables using MySQL commands
▪ A script file is used to make the typing easier
▪ Tables are named with plural names because of Rails names
corresponding classes with the singular
▪ Model classes are created
ruby script/generate model corvette
▪ Directives in the model files specify the table relations
– has_many
– belongs_to
Building the Application
▪ A table object gives access to the data in the table
– Method count gives the number of rows
– Method find is used to search
▪ Method find
– One parameter is a primary key search. The matching row is returned
– Parameter :all requires a second parameter giving the value of the :conditions
symbol, a test condition. All matching rows are returned
– Parameter :first requires a second parameter giving the value of the :conditions
symbol, a test condition. The first matching row is returned
▪ Method find_by_sql takes an SQL SELECT command
▪ The action methods query the database and put results into instance variables
▪ The matching template displays the results
Layouts
▪ A layout template provides a standard template for other templates
– Put in the layouts directory
– Put a layout command in the ApplicationController class
▪ The layout template can provide header and styling directions while
other templates provide content
▪ The @content_for_layout variable in the layout template provides
the content from the other template
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE