Module2 Notes (Srinivasulu M)
Module2 Notes (Srinivasulu M)
Module -2
Introduction to Ruby and Introduction to Rails
Control statements
Arrays, Hashes
Pattern matching
Methods, Classes
Overview of Rails
Document requests
Textbook to be referred:
Robert.W. Sebesta : Programming the Worldwide Web, 4th Edn, Pearson, 2012
Data types
Numeric String
Integer Float
Fixnum Bignum
Numeric Literals
All Numeric data types in Ruby are descendants of the Numeric class.
The integer class has two child classes – Fixnum object and Bignum object.
The Integer literal that fits into the range of a machine word, which is often 32 bits, is a
Fixnum object.
An Integer literal that is outside the Fixnum object range is a Bignum object.
If a Fixnum integer grows beyond size limitation of Fixnum object, it is coerced to Bignum
object.
Underscore characters can appear embedded in integer literals. Ruby ignores such
underscores. Example: instead of 124761325, can be used as 124_761_325.
The decimal point must be embedded, that is, it must be both preceded and followed by at
least one digit. Example: 0.1 is legal but .1 is not a legal literal.
Ruby does not require to use semicolon at the each statement end of the line.
String Literals
All string literals are String objects, which are sequence of bytes that represent characters.
The null string (one with no characters) can be denoted with either ' ' or " ".
Single quotes:
Example: 'Welcome to UBDTCE '
Single-quoted string literals cannot include escape sequence characters. Such as \n,\t etc...
Example: 'Welcome to \n UBDTCE ' #the output will be as it is it will print.
— If a single-quoted string literal is needed special symbols, then it must be embedded with
single-quote and preceded by a backslash. Example: 'Welcome to \'MCA' department’.
— Instead of single–quotes, we can also use different delimiter to represent a single-quote
string literal. It should start with q and followed by any special characters and ended with
same special characters. Example: q$ Welcome to UBDTCE $ or q< Welcome to UBDTCE >
Double quotes:
Example: "Welcome to UBDTCE "
Double-quoted string literals cannot include escape sequence characters. Such as \n,\t etc...
Example: "Welcome to \n UBDTCE "
— The values of a variable names can be interpolated into the string.
— A double quote can be embedded in a double-quote string literal by preceding it with a
backslash.
— Instead of double –quotes, we can also use different delimiter to represent a double-quote
string literals. It should start with Q and followed by any special characters and ended
with same special characters.
Example: Q@ Welcome to UBDTCE @ or Q% Welcome to UBDTCE %
Example: irb
irb(main):001:0>5*6
=>30
irb(main):002:0>3+4
=>7
irb(main):003:0>6+4
=>10
The default prompt can be changed with the following command
irb(main):001:0> conf.prompt_i = ">>"
Now the new prompt is: >>
Output is directed to the screen with the puts method (or operator).
Example: >>name="Rohit"
=> "Rohit"
>>puts "my name is #{name}"
my name is Rohit
=> nil
The value returned by puts is nil, and that value is returned after the string has been
displayed.
Keyboard Input:
The gets method gets a line of input from the keyboard, default it will be taken as string.
Example: >>fruit=gets mango
=> "mango\n"
If a number is to be input from the keyboard, the string from gets must be converted to an
integer with to_i method.
If the number is a floating-point value, the conversion method is to_f.
Example: >> age=gets.to_i
23
=> 23
>> age=gets.to_f
23.5
=> 23.5
Example Program:
Write a program to input four numbers a, b, c, x and find the value of the expression
ax2+bx+c
#!/usr/bin/ruby
puts “ enter the values of a”
a=gets.to_i
puts “enter the value of b”
b=gets.to_i
puts “enter the value of c”
c=gets.to_i
puts “enter the value of x”
x=gets.to_i
result= a*x**2+b*x+c
puts “ the value of the expression is: #{result}”
String Methods
The ruby String class has more than 75 methods, a few of which are:
Page 5
Module 2 [18MCA42] Advanced Web Programming
rstrip Removes the spaces on the right end >>rnsit=" hello "
=> " hello "
>>rnsit.rstrip
=> " hello"
reverse Reverse the characters of the string >>rnsit=" hello "
=> " hello "
>>rnsit.reverse
=> " olleh "
swapcase Convert all uppercase letters to lowercase and all >>rns="RaVi"
lowercase letters to uppercase => "RaVi"
>>rns.swapcase
=> "rAvI"
Page 6
Module 2 [18MCA42] Advanced Web Programming
Catenation method
The String method for catenation is specified by plus (+), which can be used as binaryoperator.
Example: >> "Happy" + "" + "Morning"
=> "Happy Morning"
Assignment method
Example: >> a = "Happy"
=> "Happy"
>> b = a
=> "Happy"
>> b
=> "Happy"
<< method
To append a string to the right end of another string, use the << method.
Example: >> a = "Happy"
=> "Happy"
>> a << "Morning"
=> "Happy Morning"
Chr method
Ruby strings can be indexed, the indices begin at zero. The brackets of this method specify a
getter method. The catch with this getter method is that it returns the ASCII code rather than
the character. To get the character, the chr method must be used.
Example:
Substring method
A multicharacter substring of a string can be accessed by including two numbers in the
brackets.
Example:
Page 7
Module 2 [18MCA42] Advanced Web Programming
== method
The usual way to compare strings for equality is to use the == method as an operator.
Example: >>"rnsit"=="rnsit"
=> true
>>"rnsit"=="bms"
=> false
< = > compare method
It returns -1 if the second operand is greater than the first
Example: >>"apple"<=>"grape"
=> -1
>>"grape"<=>"grape"
=> 0
>>"grape"<=>"apple"
=> 1
repetition operator
The repetition operator is specified with an asterisk (*). It takes a string as its left operand and
an expression that evaluates to a number as its right operand.
Example: >>"hello" * 5
=> "hellohellohellohellohello"
equal? method
It determines whether its parameter is the same object as the one to which it is sent.
Example: >> "snowstorm". equal? ("snowstorm")
=> false
This produces false because, although the contents of two string literals are the same, they are
different objects.
eql? method
It returns true if its receiver object and its parameter have the same types and the same value.
Example: >> 7 ==7.0
=> true
>> 7.eql?(7.0)
=> false
Operator Operation
== Is equal to
!= Is not equal to
< Is less than
> Is greater than
<= Is less than or equal to
>= Is greater than or equal
<=> Compare, returning -1, 0, or +1
Example:
#!/usr/bin/ruby
x=1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
Ruby has an unless statement, which is same as its if statement except that the inverse of the
value of the control expression is used.
Example :
unless sum > 1000
put “we are not finished yet! “
end
The Ruby while and for statements are similar to those of C and its descendants. The bodies of
both are sequences of statements that end with end.
Syntax:
while control expression
loop body statement(s)
end
Example:
$i = 0
$num = 5
while $i < $num
puts "Inside the loop i = #$i"
$i +=1
end
The until statement is similar to the while statement except that the inverse of the value of the
control expression is used.
Ruby includes two kinds of multiple selection constructs, both named case.
One Ruby case construct, which is similar to a switch, has the following form:
Syntax :
case expression
When value then
-statement sequence
When value then
-statement sequence
[else
-statement sequence]
end
The expression specified by the when clause is evaluated as the left operand. If no when
clauses match, case executes the code of the else clause.
A when statement's expression is separated from code by the reserved word then, a
newline, or a semicolon.
Example: >> in_val = gets
0
case in_val
When -1 then
neg_count += 1
When 0 then
zero_count += 1
When 1 then
pos_count += 1
else
puts "Error – in_val is out of range"
end
if the when value is a range, such as (1..100) yields true if the value of the case
expression is in given range.
$age = 5;
case $age
when 0 .. 2 then
puts "toddler";
when 3 .. 6 then
puts "kid";
when 7 .. 12 then
puts "child";
when 13 .. 18 then
puts "youth";
else
puts "adult";
end
for i in 0..5
puts "Value of local variable is #{i}"
end
break and next Statements in Ruby
break: The break statement causes control to go to the first statement following the code
block.
next: The next statement causes control to go to the first statement in the code block.
Example:
sum = 0 sum = 0
loop loop
begin begin
dat = gets.to_i dat = gets.to_i
if dat < 0 break if dat < 0 next
sum += dat sum += dat
end end
Arrays in Ruby are more flexible than those of most of the other common languages.
There are two differences between Ruby arrays and other languages such as C, C++,
and java.
— First, the length of the Ruby array is dynamic. It can grow and shrink any time
during program execution.
— Second, Array can store different types of data.
Array creation:
Ruby arrays can be created in two different ways.
First, an array can be created by sending the new message to the predefined Array
class, including a parameter for the size of the array.
Example: >>list1=Array.new(5)
=> [nil, nil, nil, nil, nil]
Page 11
Module 2 [18MCA42] Advanced Web Programming
An array created with the new method can also be initialized by including a second
parameter, but every element is given the same value.
Example: >>list3=Array.new(3,"rns")
=> ["rns", "rns", "rns"]
for-in statement
The for-in statement is used to process the elements of an array.
Example: sum=0
list=[2,4,6,8,10]
for value in list
sum+=value
end
puts sum
shift method removes and returns the first element of the array.
Example: >> ruby = [2,3,4,5,6]
=> [2, 3, 4, 5, 6]
>> first = ruby.shift
=> 2
>> ruby
=> [3, 4, 5, 6]
unshift method takes a scalar or an array literal as a parameter. The scalar or array
literal is append to the beginning of the array.
Example: >> ruby
=> [3, 4, 5, 6]
>> ruby.unshift ("mca","be")
=> ["mca", "be", 3, 4, 5, 6]
pop method removes and returns last element from the array.
push method also takes scalar or an array literal. The scalar or an array literal is
added to the high end of the array.
Example: >> ruby
=> ["mca", "be", 3, 4, 5, 6]
>> ruby.push(100,60)
=> ["mca", "be", 3, 4, 5, 6, 100, 60]
include?: The include? predicate method searches an array for a specific object.
Example: >> rns2
=> [6, 8, 7]
>> rns2.include?(6)
=> true
Set operations
There are three methods that form perform set operations on two arrays.
& for set intersection
- for set difference
| for set union.
Example:
>> set1 = [2,4,6,8] >> set1 = [2,4,6,8] >> set1 = [2,4,6,8]
=> [2,4,6,8] => [2,4,6,8] => [2,4,6,8]
>> set2 = [4,6,8,10] >> set2 = [4,6,8,10] >> set2 = [4,6,8,10]
=> [4,6,8,10] => [4,6,8,10] => [4,6,8,10]
>> set1 & set2 >> set1 - set2 >> set1 | set2
=> [4,6,8] => [2] => [2,4,6,8,10]
Hashes
Associative arrays are arrays in which each data element is paired with a key, which
is used to identify the data element.
Like arrays, hashes can be created in two ways, with the new method or by assigning
a literal to a variable.
Example: >> ages={"ravi"=>23,"raj"=>34,"kiran"=>12}
=> {"kiran"=>12, "raj"=>34, "ravi"=>23}
If the new method is sent to the Hash class without a parameter, it creates an empty
hash.
Example: >> college = Hash.new{}
New values are added to a hash by assigning the value of the new element to a
reference to the key of the new element.
Example: >> ages = {"ravi"=>23,"raj"=>34,"kiran"=>12}
>> ages["mohan"]=33
>> ages
=> {"kiran"=>12, "raj"=>34, "ravi"=>23, mohan"=>33}
Page 14
Module 2 [18MCA42] Advanced Web Programming
An element can be removed from a hash with the delete method, which takes an
element key as a parameter.
Example: >> ages
=> {"kiran"=>12, "raj"=>34, "ravi"=>23, mohan"=>33}
>> ages.delete("raj")
=> 34
>> ages
=> {"kiran"=>12, "ravi"=>23, "mohan"=>33}
In Ruby, there are some few iterator methods are designed to use blocks.
— times iterator
— each iterator
— upto iterator
— step iterator
— collect iterator
times iterator
The times iterator method provides a way to build counting loops. The times method
repeatedly executes the block.
Example: 3.times {puts "hello"}
hello
hello
hello
=> 3
each iterator
The most commonly used iterator is each, which is often used to go through arrays and
apply a block to each element. Blocks can have parameters, which appear at the
beginning of the block, delimited by vertical bars ( | ).
Example: >> list10 = [1, 2, 4, 5]
=> [1, 2, 4, 5]
>> list10.each {|value| puts value}
1
2
4
5
=> [1, 2, 4, 5]
upto iterator
The upto iterator method is used like times, except that the last value of the counter is
given as a parameter.
Example: >> 4.upto (8) {|value| puts value}
4
5
6
7
8
step iterator
The step iterator method takes a terminal value and step size as parameters and
generated the value from that of the object to which it is sent and the terminal value.
Example: >> 2.step (4,1) {|value| puts value}
2
3
4
collect iterator
The collect iterator method takes the elements from an array, one at a time, like each,
and puts the value generated by the given block into a new array.
Example: >> list15 = [5,10,15,20]
=> [5, 10, 15, 20]
>> list15.collect {|value |value = value-5}
=> [0, 5, 10, 15]
Substitutions:
Sometimes the substring of a string that matched a pattern must be replaced by
another string.
The substitute method, sub, takes two parameters, a pattern and a string.
Example: >> str = "we belong to rnsit family. rnsit"
=> "we belong to rnsit family. rnsit"
>> str.sub(/rnsit/,"rns")
=> "we belong to rns family. rnsit"
— 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 rnsit family. rnsit"
>> str.gsub (/rnsit/,"rns")
=> "we belongs to rns family. rns"
— 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?"
A method header is the reserved word def, the method’s name, and optionally a
parenthesized list of formal parameters.
You can set default values for the parameters which will be used if method is called
without passing required parameters:
Syntax: def method_name (var1=value1, var2=value2)
statements….
end
Example:
Local variables
• Local variables are either formal parameters or are variables created in a method.
• The scope of the local variable is from the header of the method to the end of the
method.
• Local variables must be begin with either a lowercase letter or an underscore ( _ ).
• Beyond the first character, local variable names can have any number of letters,
digits, or underscores.
• The lifetime of the local variable is from the time it is created until end of the
execution of the method.
• The return statement in ruby is used to return one or more values from a Ruby
Method.
Example:
#!/usr/bin/ruby
def test
i = 10
j = 20
k = 30 local variables
z=#{i+j+k};
return z
end
Parameters:
• In Ruby, parameters transmission of scalars is strictly one-way into the method.
• The value of the scalar actual parameters are available to the method through its
formal parameters.
Example:
def swap(x,y)
t = x
x = y
y = t
puts "the values are #{x},#{y}"
end
a=1
b=2
swap(a,b)
Classes
end
A class in Ruby always starts with the keyword class followed by the name of the
class.
The name should always be in initial capitals.
The initialize method is a special type of method, which will be executed when the
new method of the class is called with parameters.
Ex:
class Customer
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
end
Page 20
Module 2 [18MCA42] Advanced Web Programming
Access Control:
Access control in Ruby is different for access to data than it is for access to methods.
All instance data has private access by default, and it cannot be changed,
The equal sign (=) attached to the name of the setter method means that the method
is assignable. So, all setter methods have equal signs attached to their names.
Ruby provides shortcuts for getter and setter methods. Those are attr_reader and
attr_writer.
attr_reader (getter) is actually method call, using the symbols :one and :two as the
actual parameters.
Example: attr_reader : one, :two
The three levels of access control for methods are defined as follows,
— public: access means the method can be called by any code.
— protected: access means that only objects of the defining class and its
subclasses may call the method.
— private: that the method cannot be called with an explicit receiver object.
Because the default receiver object is self, a private method, can only be called
in the context of the current object.
Example :
class My_class
def meth1
....
end
private
def meth7
....
end
protected
def meth11
....
end
end
Class variables begin with @@ and must be initialized before they can be used in
method definitions.
Example :
class Customer
@@no_of_customers=0
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr“
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
Page 22
Module 2 [18MCA42] Advanced Web Programming
Embedded Ruby
• Ruby provides a program called ERB (Embedded Ruby), written by Seki Masatoshi.
• ERB allows you to put Ruby codes inside an HTML file.
• ERB reads along, word for word, and then at a certain point, when it encounters a
Ruby code embedded in the document, it starts executing the Ruby code.
• You need to know only two things to prepare an ERB document :
— If you want some Ruby code executed, enclose it between <% and %>.
— If you want the result of the code execution to be printed out, as a part of the
output, enclose the code between <%= and %>.
RHTML is HTML mixed with Ruby, using HTML tags. All of Ruby is available for
programming along with HTML.
Demo.rhtml
<% page_title = "Demonstration of ERB" %>
<% salutation = "Dear programmer," %>
<html>
<head>
<title>hello ruby </title>
</head>
<body>
<p><%= salutation %></p>
<p><%= page_title %></p>
</body>
</html>
output
Dear programmer
Demonstration of ERB
Page 23
Module 2 [18MCA42] Advanced Web Programming
Rails, because of its intimate connection with Ruby, is often called Ruby on Rails or
simply RoR.
Rails was developed by David Heinemeier Hansson in the early 2000s and was
released to the public in July 2004.
You could develop a web application at least ten times faster with Rails than you
could with a typical Java framework.
To develop a web application using Ruby on Rails Framework, you need to install the
following software − Instant -Rails
— Ruby
— Rails Framework
— Apache Web Server
— MySQL
MVC Architecture
Rails is based on Model-View-Controller (MVC) architecture for applications.
The model (ActiveRecord) is belongs to the Data or Database and all its queries
parts.
The view (ActionView) is the part of an application that prepares and presents
results to the user nothing but on the browser. The view documents are generated
three categories of view documents, XHTML, XML, and JavaScript.
Working:
In an MVC web application, a browser submits request to the controller, which
consults the model and reports results back to the controller and indirectly to the
view.
The controller then instructs the view to produce a result document that is then
transmitted to the client for display.
The intent of MVC is to reduce the coupling among the three parts of an
application, making the application easier to write and maintain.
The view and controller parts of MVC is supported with the ActionPack component
of Rails. They are packed in the same component, the code support for the view and
controller are cleanly separated.
This topic describes how to demonstrate the structure of the simplest possible
Rails application and showing what files must be created and where they must be
resided in the directory structure.
First, you just click on Instant Rails icon. You will get the following small window.
Here, you click on black I on the left border of this window produces a small menu.
Click the Rails Application entry in this menu, which opens another menu.
Clicking on the Open Ruby Console Window entry in this menu opens a DOS command
window in the following directory.
C:\InstantRails-2.0\rails_apps
To this base directory, users usually add a new subdirectory for all their Rails applications.
We named ours lab1. In the new lab1 directory, the new application rails is created with
the following command.
rails lab1
Rails responds by creating more than 40 files in more than 15 directories. This is part of
the framework to support a Rails application. In this case lab1, 12 subdirectories are
created.
Now change to new directory, just typing: cd lab1
The most interesting of which at this point is app. The app directory has four
subdirectories-models, views, controllers and helpers. The helpers subdirectory contains
Rails-provided methods that aid in constructing applications.
One of the directories created by the rails command is script, which has several important
Ruby scripts that perform services. This script creates two Ruby controller methods and
also a subdirectory of the views directory where views code will be stored.
In the above output exists lines indicate files and directories that are verified to already
exist.The create lines show the newly created directories and files.
There are now two Ruby classes in the controllers directory, application.rb and
say_controller.rb. where the say_controller.rb class is a subclass of application.rb.
Saycontroller is an empty class, other than what it inherits from application.rb. The
controller produces, at least indirectly, the response to requests, so a method must be
added to SayController subclasses.
Next we need to build the view file which will be simple like XHTML file to produce the
greeting. The view document is often called template. The following is the template for the
lab1 applications.
> notepad app\Views\say\hello.rhtml
hello.rhtml
<DOCTYPE >
<html>
<head> <title> Simple Document </title>
</head>
<body>
<h1> Hello Welcome </h1>
</body>
</html>
The extension on this file is .rhtml, templates can include ruby code, which is
interpreted by a ruby interpreter named ERb (Embedded Ruby), before the template is
return to the requesting browser.
Before the application can be tested, a rails web server must be started. A server is
started with server script from the script directory.
ruby script/server
Rails there are three different servers available. The default server is Mongrel, but apache
and WEBrick are also available in rails.
The default port is 3000. If a different port must be used, because 3000 is already being
used by some other program on the system, the port number is given as a parameter to the
server script.
The server name is always localhost because its running in the same machine on
which applications resides.
Output:
Dynamic Documents
Rails offers three different approaches to producing dynamic documents. Here we discussed
only one, which is to embed Ruby code in a template file. This is similar to some other
approaches we have discussed, in particular PHP, ASP.NET and JSP.
Ruby code is embedded in a template file by placing it between the <% and %> markers.
If the Ruby code produces a result and the result is to be inserted into the template
document, and equal sign (=) is attached to the opening marker.
The date can be obtained by calling Ruby’s Time.now method, this method returns current
day of the week, month, day of the month, time, time zone, and year, as a string.
[Note: The above (static document) procedure is same to develop a new rails applications]
main_controller.rb
class MainController < ApplicationController
def timer
@t = Time.now
end
end
timer.rhtml
<DOCTYPE >
<html>
<head> <title> Simple Document </tittle>
</head>
<body>
<h1> Hello Welcome </h1>
<p> It is now <%= @t %> </p>
</body>
</html>
The contents of the form.rhtml is exactly the same as the HTML files, except that the
opening form tag appears as follows.
This specifies that the name of the action method in the application’s controller, as well as
the template for the result of submitting the form, is result.
This tag specifies the POST HTTP method. Rails requires that POST be used.
Now, we point our browser to the following: http://localhost/home/the_form
In the initial template file, the_form.rhtml, this method is named result in the action
attribute of the form tag.
The result method has two tasks, the first of which is to fetch the form data. This data
is used to display back to the customer and to compute the result.
The form data is made available to the controller class through the Rails-defined
object, params. Params is a hash-like object that contains all of the form data. It is a hash-
like because it is a hash that can be indexed with either symbols or actual keys. The
common Rails convention is to index params with symbols.
home_controller.rb
Class HomeController< ApplicationController
def form
end
def result
@phone_no = params[:phone]
end
end
form.rhtml
<html>
<head><title>input
form</title></head>
<body>
<form action ="result" method = "post">
Phone:<input type="text" name="phone"/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
result.rhtml
<html>
<head><title>input form</title></head>
<body>
<h4> the given phone number<%=@phone_no%>is valid</h4>
</body>
</html>
Output:
2.12 Layouts.
The views directory of each application has two subdirectories, one that has the name of
the controller and another subdirectory named layouts.
Rails creates the layouts subdirectory, but leaves it empty.
The user can create a layout template and place it in the layouts directory.
It provides a way to put some boilerplate markup into each template file in the application.
Notice that the value of the predefined instance variable @content_for_layout is inserted
in the body of the layout document.
Find method
This method searches its table for rows that satisfy given criteria. The find method
have two parameters. The first parameter to find is :all, find searches can be
controlled by a second parameter, which is specified as the value of the :conditions
symbol.
@book_name = params[:sname]
@bookz = find(:all, conditions => "name = ' #{@book_name}' ")