0% found this document useful (0 votes)
34 views33 pages

Module2 Notes (Srinivasulu M)

Uploaded by

AYESHA SIDDIQA K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views33 pages

Module2 Notes (Srinivasulu M)

Uploaded by

AYESHA SIDDIQA K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Module 2 [18MCA42] Advanced Web Programming

Module -2
Introduction to Ruby and Introduction to Rails

 Origins and uses of Ruby

 Scalar types and their operations

 Simple input and output

 Control statements

 Arrays, Hashes

 Code blocks and iterators

 Pattern matching

 Methods, Classes

 Overview of Rails

 Document requests

 Processing forms, Layouts.

 Rails applications with Databases.

Textbook to be referred:
Robert.W. Sebesta : Programming the Worldwide Web, 4th Edn, Pearson, 2012

ROOPA.H.M, Dept of MCA, RNSIT Page 1


Module 2 [18MCA42] Advanced Web Programming

2.1 Origins and Uses of Ruby


 Ruby was designed in Japan by Yukihiro Matsumoto and was released in 1996.
 It started as a replacement of the Perl and Python language.
 Ruby is pure Object-oriented programming language, its variables are all references to
Object.
 Every data value in Ruby is an Object.

2.2 Scalar types and their operations


Ruby has three categories of data types – Scalars, Arrays and Hashes.
Scalars: There are two categories of scalar types – Numeric Literals and String Literals

Data types

Arrays Scalars Hashes

Numeric String

Integer Float

Fixnum Bignum

Numeric Literals

 All Numeric data types in Ruby are descendants of the Numeric class.

 The immediate child classes of Numeric are Integer and Float.

 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.

 If an operation on a Bignum object results in a value that fits in a Fixnum object, it is


coerced to a Fixnum 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.

ROOPA.H.M, Dept of MCA, RNSIT Page 2


Module 2 [18MCA42] Advanced Web Programming

 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.

 Strings can be represent either in single-quotes or double-quotes.

 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 %

Variables and Assignment Statements


There is no data-type to declare a variable.
 The identifier must start with a lowercase letter or underscore, followed by any number of
uppercase or lowercase letters, digits or underscore.
 The letters in a variable name are case sensitive. Example: abc, ABC are all distinct.
 Programmer defined variable names do not include uppercase letters.
 Double-quoted string literals can include the values of variables. This is specified by placing
the code in braces and preceding the left brace with a pound sign (#).
Example: temp=32
puts "Todays high temperature is: #{temp}"
puts "The cost is : #{temp * 2 }"
 Ruby includes some predefined or implicit variables. The names of implicit scalar variables
begin with dollar signs. The rest of the name of an implicit variable is often just one more
special characters, such as an underscore( _ ), a circumflex( ^ ), or a backslash( \ ).

ROOPA.H.M, Dept of MCA, RNSIT Page 3


Module 2 [18MCA42] Advanced Web Programming

Numeric Operators Binary Operators:


 Binary operators are + for addition, - for subtraction, * for multiplication, / for division, ** for
exponentiation, and % for modulus.
 Ruby does not include the increment (++) and decrement (--) operator.
 Ruby includes the Math module, which has methods for basic trigonometric functions. Such
as Math.cos(x), Math.sin(x), Math.log(x), Math.sqrt(x), and Math.tan(x). where x is a parameter
to be passed.
 Ruby have interactive interpreter. It allows one to type any ruby expression and get immediate
response from the interpreter.
 The interactive interpreter’s name is Interactive Ruby. Whose acronym, irb is the name of the
program that supports it.
 Simply typing irb at the command prompt in the directory that contains the ruby interpreter.
Example: >irb
irb will response with its own prompt, which is: irb(main):001:0>
At this prompt, any Ruby expression or statement can be typed. irb interprets the expression
or statement and returns the value after an implication symbol(=>).

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: >>

2.3 Simple input and output


Screen Output

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.

ROOPA.H.M, Dept of MCA, RNSIT Page 4


Module 2 [18MCA42] Advanced Web Programming

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:

 Catenation method (+)


 Assignment method
 << method
 chr method
 substring method
 == method
 equal? method
 eql? method
 < = > compare method

Page 5
Module 2 [18MCA42] Advanced Web Programming

The other most commonly used methods are

Method Action Examples

capitalize Convert the first letter to uppercase and >>str="MCA"


the rest of the letters to lowercase => "MCA"
>>str.capitalize
=> "Mca"
chop Removes the last character >>str="MCA "
=> "MCA "
>>str.chop
=> "MCA"
chomp Removes a newline from the right end, if >>strg="mca\n"
there is one => "mca\n"
>>strg.chomp
=> "mca"
upcase Converts all lowercase to uppercase >>str="Good"
=> "Good"
>>str.upcase
=> "GOOD"
downcase Converts all uppercase to lowercase >>str="MCA"
=> "MCA"
>>str.downcase
=> "mca"
strip Removes the spaces on both ends >>rnsit=" hello "
=> " hello "
>>rnsit.strip
=> "hello"
lstrip Removes the spaces on the left end >>rnsit=" hello "
=> " hello "
>>rnsit.lstrip
=> "hello "

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:

>> be="civil" >> be="civil"


=> "civil" => "civil"
>> be[2] >> be[2].chr
=> 118 => "v"

 Substring method
A multicharacter substring of a string can be accessed by including two numbers in the
brackets.

Example:

>> city="bangalore" >> name="Donald"


=> "bangalore" => "Donald"
>> city[3,3] >> name[3,3]="nie"
=> "gal" => "nie"
>> name
=> "Donnie"

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

0, if they are equal

1, if the first operand is greater than second

Greater in this case means it belongs later in alphabetical order.

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

ROOPA.H.M, Dept of Page 8


Module 2 [18MCA42] Advanced Web Programming

2.4 Control statements


Relational Operator used in control statements

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

Selection and Loop Statement


Ruby’s if statement is similar to that other languages. One syntactic difference is that there are
no parentheses around the control expression.

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

ROOPA.H.M, Dept of MCA, RNSIT Page 9


Module 2 [18MCA42] Advanced Web Programming

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

ROOPA.H.M, Dept of MCA, RNSIT Page 10


Module 2 [18MCA42] Advanced Web Programming

The general syntax for for statement is


for variable in expression [do]
code
end
Example:

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

2.5 Arrays, Hashes


Fundamentals of Arrays

 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"]

 Second, to assign a list literal to a variable.


Example: >>list2=[2,4,6,"rns",2]
=> [2, 4, 6, "rns", 2]

The length of an array can be retrieved with the length method.


Example: >>list3.length
=> 3

Accessing array elements


All Ruby array elements use integers as subscripts, and the lower-bound subscript of
every array is zero. Array elements are referenced through subscripts delimited by
brackets([ ]), which is actually a getter method that is allowed to be used as a unary
operator. Likewise, [ ]= is a setter method which sets the value for specified position.
Example: >>ruby=[2,4,6,8,9]
=> [2, 4, 6, 8, 9]
>>a=ruby[2] #getter method [ ]
=> 6
>>ruby[3]=10 #setter method [ ]=
=> 10
>>ruby
=> [2, 4, 6, 10, 9]

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

Built-in methods for Arrays and Lists


unshift and shift: which deal with the left end of arrays.
pop and push: which deal with right end of arrays.

ROOPA.H.M, Dept of MCA, RNSIT Page 12


Module 2 [18MCA42] Advanced Web Programming

 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]

concat: If an array is to be catenated to the end of another array, concat is used.


Example: >> rns1 = [1,2,3]
=> [1, 2, 3]
>> rns2 = [6,8,7]

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]

ROOPA.H.M, Dept of MCA, RNSIT Page 13


Module 2 [18MCA42] Advanced Web Programming

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.

 The two difference between arrays and hashes are:


— First, arrays use numeric subscripts to address specific elements whereas hashes
us keys to address elements.
— Second, the elements in arrays are ordered by subscripts but the elements in
hashes are not.

 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{}

 An individual value element of a hash can be referenced by subscripting the hash


name with the key.
Example: >> ages = {"ravi"=>23,"raj"=>34,"kiran"=>12}
=> {"kiran"=>12, "raj"=>34, "ravi"=>23}
>> ages["ravi"]
=> 23

 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}

 A hash can be set to empty in two ways:


— First, an empty hash literal can be assigned to the hash.
Example: >> ages={}
=> {}
— Second, the clear method can be used on the hash.
Example: >> ages.clear
=> {}
 has_key?
Predicate method is used to determine whether an element with the specific key is in a
hash.
Example: >> ages.has_key?(“ravi”)
=> true
 keys and values
Hash can be extracted into arrays with the methods keys and values.
Example: >> rnsit={"mca"=>12,"mba"=>10,"puc"=>6}
=> {"mca"=>12, "mba"=>10, "puc"=>6}
>> rnsit.keys
=> ["mca", "mba", "puc"]
>> rnsit.values
=> [12, 10, 6]

2.7 Code blocks and iterates


 A block is a segment of code, delimited by either braces or the do and end reserved
words.
 Blocks can be used with specially written methods to create many useful constructs,
including simple iterators for arrays and hashes.

 This construct consists of a method call followed by a block.

 In Ruby, there are some few iterator methods are designed to use blocks.
— times iterator
— each iterator
— upto iterator
— step iterator
— collect iterator

ROOPA.H.M, Dept of MCA, RNSIT Page 15


Module 2 [18MCA42] Advanced Web Programming

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]

ROOPA.H.M, Dept of MCA, RNSIT Page 16


Module 2 [18MCA42] Advanced Web Programming

2.8 Pattern matching


The basics of Pattern matching:
 In Ruby, the pattern-matching operation is specified with the matching operators,
=~.
 Patterns are placed between slashes(//).
Example: >> pattern = "good morning"
=> "good morning"
>> pattern =~ /g/
=> 0
>> pattern =~ /r/
=> 7
>> pattern =~ /z/
=> nil
Remembering matches:
— The part of the string that matched a part of the pattern can be saved in an implicit
variable for later use.
Example: >> date="04 april 2021"
=> "04 april 2021"
>> date =~ /(\d+) (\w+) (\d+)/
=> 0
>> puts "#{$2} #{$1},#{$3}"
=>april 04,2021

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?"

ROOPA.H.M, Dept of MCA, RNSIT Page 17


Module 2 [18MCA42] Advanced Web Programming

2.9 Methods , Classes


Methods

 A method definition includes the method’s header and a sequence of statements,


ending with the end reserved word, which describes its actions.

 A method header is the reserved word def, the method’s name, and optionally a
parenthesized list of formal parameters.

 Method name must begin with lowercase letters.

 If the method has no parameters, the parentheses are omitted it means no


parentheses.
Syntax: def method_name
statements….
end

 You can represent a method that accepts parameters like this:


Syntax: def method_name (var1, var2)
Statements.....
end

 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:

def test(a1="Ruby", a2="Perl")


puts " programming language is #{a1}"
puts "The programming language is #{a2}"
end

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.

ROOPA.H.M, Dept of MCA, RNSIT Page 18


Module 2 [18MCA42] Advanced Web Programming

• 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

var = test // function call


puts var

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

 Classes in Ruby are like those of other object-oriented programming languages.

 A class is the blueprint from which individual objects are created.

 Instance variables begin with @.


Defining a Class in Ruby:
class Customer

end

ROOPA.H.M, Dept of MCA, RNSIT Page 19


Module 2 [18MCA42] Advanced Web Programming

 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 class should be end with the keyword end.


Object Creation:

 Objects are instances of the class.


 You can create objects in Ruby by using the method new of the class.

 The new method belongs to the class methods.


Ex:
cust1 = Customer. new
cust2 = Customer. new

 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

cust1=Customer.new("1", "ram", “bangalore")


cust2=Customer.new("2", "ravin", “delhi")

Member Functions in Ruby Class


• In Ruby, functions are called methods. Each method in a class starts with the
keyword def followed by the method name.
• The method name always preferred in lowercase letters. End of a method in Ruby id
denoted by using the keyword end.
Syntax: Example:
class Sample class Sample
def function def mca
statement 1 puts "Hello Ruby!"
statement 2 end
end end
end
rnsit = Sample.new //object creation
rnsit.mca //method access

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,

 If external access to an instance variable is required, access methods must be


changed.
Example:
class My_class
def initialize
@one = 1
@two = 2
end

# A getter for @one


def one
@one
end

# A setter for @one


def one = (my_one)
@one = my_one
end
end

 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

attr-writer (setter)as similarly creates setter method.

 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.

ROOPA.H.M, Dept of MCA, RNSIT Page 21


Module 2 [18MCA42] Advanced Web Programming

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

cust1=Customer.new(1, “Kiran", “Bangalore")


cust2=Customer.new(2, “Ravi", “Hyderabad")
cust1.total_no_of_customers()
cust2.total_no_of_customers()
Output:
Total number of customers:1
Total number of customers:2

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

2.9 Overview of Rails


 Rails is a web application development framework written in the Ruby language.
 A framework is a program, set of programs, and/or code library that writes most of
your application for you.
 A web application development framework is a software framework that is designed
to support the development of websites, web applications, web services and web
resources.

 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.

 MVC was developed by Trygve Reenskaug,a Norwegian, in 1978-1979.

 The MVC architecture is clearly separates applications into three parts.

 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.

 The controller (ActionController), the controller part of MVC, controls the


interactions between the data model, the user, and the view.

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.

ROOPA.H.M, Dept of MCA, RNSIT Page 24


Module 2 [18MCA42] Advanced Web Programming

 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.

 Ruby on Rails is completely Object-Oriented-Programming language, whereas


the Database is completely Relational-Database.
 These two are different platforms, so, this is not a natural connection. For this
Rails uses an Object- Relational-Mapping (ORM) approach.
 Each relational database tables is implicitly mapped to a class.
Example:
 An ORM maps database Tables to Classes,
 Rows to Objects, and
 Table Columns to the fields of the Object methods.

2.10 Document requests


Static Documents

 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.

ROOPA.H.M, Dept of MCA, RNSIT Page 25


Module 2 [18MCA42] Advanced Web Programming

 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.

 generate is used to create part of an application controller.


 For our application, we pass two parameters to generate, the first of which is
controller, which indicates that we want the controller class built. Second parameter is the

ROOPA.H.M, Dept of MCA, RNSIT Page 26


Module 2 [18MCA42] Advanced Web Programming

name we chose for the controller.


 The following command is given in the lab1 directory to create the controller.

ruby script/generate controller say


 Here say is the name of the controller. The response produced by the execution of this
command as follows:
exists app/controllers/ exists
app/helpers/ create app/views/say
create app/controllers/say_controller.rb

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.

Example: class SayController < ApplicationController


end

 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.

> notepad app\Controllers\say_controller.rb


say_controller.rb
class SayController < ApplicationController
def hello
end
end

 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.

ROOPA.H.M, Dept of MCA, RNSIT Page 27


Module 2 [18MCA42] Advanced Web Programming

 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.

 The complete URL of our application is: http://localhost/say/hello

Output:

The directory structure for the rails1 application

ROOPA.H.M, Dept of MCA, RNSIT Page 28


Module 2 [18MCA42] Advanced Web Programming

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.

Example: The number of seconds in a day: <%=60 * 60 * 24%>


Output: The number of seconds in a day: 86400

 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.

Example: <p>It is now<%= Time.now %></p>


Output: It is now May 06 10:12:23 2015

[Note: The above (static document) procedure is same to develop a new rails applications]

1) Create a new directory: > rails lab2


2) Now change to new directory: > cd lab2
3) Generate a new Controller : > ruby script/generate controller main
4) Open timer Controller: > notepad app\Controllers\main_controller.rb

main_controller.rb
class MainController < ApplicationController
def timer
@t = Time.now
end
end

ROOPA.H.M, Dept of MCA, RNSIT Page 29


Module 2 [18MCA42] Advanced Web Programming

5) Create a timer.rhtml under views\Main: > notepad app\Views\Main\ timer.rhtml

timer.rhtml
<DOCTYPE >
<html>
<head> <title> Simple Document </tittle>
</head>
<body>
<h1> Hello Welcome </h1>
<p> It is now <%= @t %> </p>
</body>
</html>

6) Start Ruby Server: >ruby script/server


7) URL link is: > http://localhost:3000/Main/timer

2.11 Processing forms


1) Setting Up the Application
 The new directory and generate a controller named home with the following command.
>ruby script/generate controller home

 The contents of the form.rhtml is exactly the same as the HTML files, except that the
opening form tag appears as follows.

<form action = "result" method = "post">


Phone: <input type="text" name="phone"/>
<input type="submit" value="OK"/>
</form>

 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

2) The controller and the View


 Next step of the construction of the application is to build the action method in
home_controller.rb to process the form data when the form is submitted.

 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

ROOPA.H.M, Dept of MCA, RNSIT Page 30


Module 2 [18MCA42] Advanced Web Programming

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.

Example: @phone_no = params[:phone]


 In above example :phone is a key and params is hash-like object, and the value
of the phone will be stored into instance variable phone_no.

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:

ROOPA.H.M, Dept of MCA, RNSIT Page 31


Module 2 [18MCA42] Advanced Web Programming

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.

 A layout template is a template for other templates.

 It provides a way to put some boilerplate markup into each template file in the application.

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>CARS</title></head>
<body >
<h1>aidan’s used car Lot</h1>
<%=@content_for_layout%>
</body>
</html>

 Notice that the value of the predefined instance variable @content_for_layout is inserted
in the body of the layout document.

2.13 Rails applications with Databases.


 Building the Database
MySQL must be started. This is done with the following command given at the command
prompt in the:
C:\InstantRails-2.0\rails_apps> mysql [-h host] [-u username]
[database_name] [-p password]

C:\InstantRails-2.0\rails_apps> mysql –u root

 Now it will login to the mysql command mysql>


 Now we can create a database and its tables. To construct the database, the Rails
applications to use three copies of the database, one for development, one for testing
and one for production. 

 For this example, we are creating a single database , databasename_development 


Example:
 Creating database
mysql> create database WebApp;

 Here we are using the database


mysql> use WebApp;

ROOPA.H.M, Dept of MCA, RNSIT Page 32


Module 2 [18MCA42] Advanced Web Programming

 To see all databases,


mysql> show databases;

 Now we must create table.


mysql> create table book ( id int not null auto_increment,
name varchar(80) not null, description text not null,
price decimal(8, 2) not null, primary key(id) );
Query OK, 0 rows affected (0.03 sec)

2) Building the Application

The inbuilt methods are count and find.


 Count method:
The number of rows in a table can be determined by calling the count method on the
table’s object.
@num_books = Books.count

 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}' ")

ROOPA.H.M, Dept of MCA, RNSIT Page 33

You might also like