Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
32 views44 pages

Scripting Languages U-1

The document provides an introduction to Ruby and Rails, covering basic concepts, package management with RubyGems, and web application development using CGI scripts. It outlines learning objectives, including the creation of simple Tk applications and understanding of SOAP and web services. Additionally, it includes short questions and answers about Ruby's features, uses, and programming constructs.

Uploaded by

csecmailid
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)
32 views44 pages

Scripting Languages U-1

The document provides an introduction to Ruby and Rails, covering basic concepts, package management with RubyGems, and web application development using CGI scripts. It outlines learning objectives, including the creation of simple Tk applications and understanding of SOAP and web services. Additionally, it includes short questions and answers about Ruby's features, uses, and programming constructs.

Uploaded by

csecmailid
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/ 44

UN0T Ttie

Introduction SIA GROUP

SIAG SROUP

(Syllabus
Intreduction: Ruby, Rails, The Structure and Execution of Ruby Programs, Package Management with
RUBYGEMS, Ruby ond Web: Writing CGI Seripts, Cookies, Choice of Webservers, SOAP and Webservices.
RubyTk - Simple Tk Application, Widgets, Binding Events, Canvas, Scrolling.

LEARNING OBJECTIVES

Basic Concepts of Ruby and Rails


Lexical Structure of Ruby Programs
Creation and Installation of RUBYGEMs

Writing CGIScripts
Concept of SOAP and Webservices
Creating Simple Tk Application
Different Options of Widgets
Concept of Ruby Tk like Binding Events, Canvas and Scrolling.

INTRODUCTION

Ruby is a simple object-oriented programing language developed by Yukihiro Matsumoto (Matz) in Japan.
It was released in the year 1996. The languages Python and Perl were soon replaced by Ruby due to their
limited functions. It was widely spread across the world within few years. One of the most common use of
Ruby is Rails. It is an open source language and can run on any machine independently without concern of
their platforms and architectures. This means a ruby that is developed on one machine coan run on some other
machine without any changes. Everything in ruby willbe considered as an object. Actions in it are çalled as
methods and properties are called as instance variables.

A ruby program is parsed like a sequence of tokens by the interpreter. RubyGems is defined as a
standardized package, installation framework for ibraries and applications. WEBrick is used for running
ruby scripts. One of the ways to implement web applications using ruby is by running the ruby program
as CGl programs. Moreover, ruby applications consists of various extensions like GTK, Fox etc.
SPESTRUM ALLANONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES SJNTU-HYDERABAD)
1.2

SHORT QUESTIONSWITH SOLUTIONS


TART-A
Q1. Write a short notes on Ruby.
Answer : Model Paper-lil, Q1(a
Ruby is a simple objcct-oriented programing language developed by Yukihiro Matsumoto. It is an open source language and
ruby
architectures. This means a that
considered as an is
objectdevel
. Actoipeaong
can run on any machine platforms and
independently without concern of their in ruby will be
on one machine can run on some Everything
other machine without any changes,
in it are called as methods and properties are called as instance
Varnaoo
Q2. llustrate the uses of ruby.
Answer : Model Paper-4, Q1:a
The following are the uses of ruby,
1. A common use of ruby is rails.

lt is ayailable for allthe computing platforms which are common.


3. The implementation of ruby is free.
It is usually used for writing the servers.
$. lt is used for experimenting with
prototypes.
6. It is also used to perform every day programming tasks.
Q3. What is meant by Ruby on Rails?
Answer :
Kails 1s a highly efficient/productive web application framework which provides a default structure for establishing the
database, web service and web pages for desired web software application. It was written in ruby by David Heinemeier Hanson.
It widely known as "Ruby on Rails". It mainly uses MVC (Model, View, Controller) pattern to provide almost all the tools tha
are required to build a web application.
The software development process ofrails is divided intothreeenvironments which are development, testing and production.
These three environments are used to perform various tasks for various purposes.
Q4. Write a short notes on literals and punctuations.
AnsWer : Model Paper-l, Q1(b)
Literals
Literals are values existing in the ruby source code which consist of the following,
(i) Numbers

(ii) Regular expressions


(iii) Strings
(iv) Array and Hash values.
Examples
100 # Integer literal
/Hundred/ # Regular expression literal
'Hundred' # String literal
Punctuation
Punctuation characters are used for writing ruby operators. These characters can be used for number of purposes including
delimitation of array, string, regular expre_sions, grouping and separating array indexes, method arguments and expressions.
Examples
* for multiplication
+ for addition
operation
I| for boolean OR
this book is aaCRIMINAL act. Anyone found guilty is
WARNING: Xerox/Photocopying of LIABLE to face LEGAL proceedings.
UNIT-1 Introduction 1.3
Q5. Discuss in brief about whitespaces.
Answer :
Model Paper-lll, Q1(b)
Ruby does not considers whitespaces, newlines and tabs as tokens. However, most of the white spaces of the
ignored, but still important tounderstand them in few cases. program are
Whitespaces are used as statement terminators i.e.. for indicating newlines. In ruby, semicolons can be used for terminating
statements. However, semicolons are used only when there are more than one statements in a same line. Ruby interpreter detects
the statement termination if the statement is complete and has significant whitespaçes after the
statement.
Q6. Define RubyGems.
Answer :

RubyCiems is defined as astandardized package, installation framework for libraries and applications which facilitate the
users and developers with the following,
1. Astandardized package format.
2. A central repository for hosting packages in the same format.
3. Installation and management of multiple, simultaneously installed versions of the same library
4. End-user tools for querying, manipulating, installing, uninstalling packages.
Q7. Discuss in brief about Ruby Extension Gems.
Answer :
Model Paper-,Q1(b)
Several ruby libraries are created as native extensions but not all gems are built with pure ruby code, there are two ways
to package and distribute such libraries as gems. They are,
1.
Distributing the gem in source format and allowing the installer to compile the code during the installation time.
2.
Pre-compiing the extensions and distributing single gem to each separate platform inorder to provide support based on
the requirement.

Ruby gems provides an attribute called extensions for the source gems, which is an array of paths to ruby files. These ruby
fles generates Makefiles using mkmf library and are named extconf.rb, which is optional. Source files must be inchuded in the
specification's files list to include them in the gem package for distribution.
Q8. Define SOAP.
Answer :

SOAP is defined as the marshaling mechanism that uses XML for exchanging data among the two nodes given in a network.
It implements remote procedure calls, RPCs, between distributed processes. ASOAP server publishes at least one interface which
is defined on data types and methods that are used. Then these interfaces on the server are connected to local proxies created by
SOAP clients. If a method is called on the proxy, then it is passed to the corresponding interface on the server and the resultant
values on the server are passed back to the client through the proxy.
Q9. Define cookies in ruby.
Answer : Model Paper-ll, Q1(a)
Cookies are defined as the storage of web applications state on the user side. They are used for remembering session
information. These cookies are handled by the ruby CGI class. So, the CGI #cookies method is used by the user to acces the
cookies that are associated with the present request. Moreover, the user can also set back the cookies into the browser by setting.
the parameter of CGI #out to reference an array of cookies or only one cookie.
Q10. Write a short note on widgets.
Answer :
Widgets are quiet easy to create and involves additions of Tk prior to the widget name in Tk documentation and used.
After adding "Tk, the widgets become classes. For example, Label - TkLabel, Entry ’ TkEntry, Button -’ TkButton. Here the
keyword 'new' can be used to create an instance of the widget. So, if aparent is not specified for the particular widget then, by
default. it directs to the root-level frame. However, the user can specify parent of a particular widget along with different options
such as size, colour, etc., based on their requirement.
When the program is in running phase, the user can retrieve the data from the widget by setting up callbacks and
sharing data.
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
BORIPING
UNIT-1
8OLUTION8
QUESTIONS WITH Example

PARTB ESBAY
I. AUY, RAILS
q1., Explaln ln datail about Ruby. Modol Papor, Q|
h|:
Answer oftheir
tevwe,
Ruby bin mea uy ibat ia developed ) one
uchin CH) FU)
mehime
withoutconcen platforms
and Arch
o) NODc other muchine Wilhout ny chanue. :veryhg
hulependetly h|:
h.
0) ny instance
melhods and propeties
ure called as
and
vriables. pr
vulled as is Cxsive
this grammar dillert
Ias a clay cOre
in uhy will beciderel an n objgt, Avtions in it re grWmar, Ilowever, progrmD,
Iis dyunic pogrumminy anpuage willh
coplex
'ogranDlDg lotetluce
(APD, I Usinspired
lithyalywith povwertil und iehApleatingramr whiclh cnnbe casily leanedMatsumolo
by
by dillerent
progranDmers ol Java
(Matz) in Japan. Il was
and languagr 3.
A
E
h as Iuall talk, perl and linp, Thun, it useN # Yukilhiro
developed by Telcaed
i annple object-oiented progmning langunge programming styles As as expres
in the ycar |900, providing tunctional and it has value.
Ilenve, it iN a pue objcet-oricnted language and can
be uned lor
ercating DSLs (Domain Specthe Tanguages).
programmin, itean even he used for functionalities, Ruby was widely
ypertmpowerulmetu by ruby due to their limited language). sprea their req
The languagen Python and Perl were Noon repluced use of'Ruby is Rails (a8 it has alsO CXpanded the
o' he most common cisy. lnstead of reading and
worid wihin few yearN, One makes the learning of ruby language
method cnlled pure interoretation interprelalOn.
An inplementation programmer ean Nimply write alogie and requcst its
writng he simple logie codc, Ruby
The following ure the busie concepts of' ruby.
Ruby is Object-orlented values lie
every thine in ruby will beconsidered as an object. This means simple
Kuby is objcct-oriented which mens "class" the aboye
on
considered as an obiect, So, a method can be invoked by a name
nl, true, lalse and numeric literals are also returns the value indicated bythe
this, comments cun begin by using character where commented code
values, Apart from
arrows( ) vailable in the conments.
Example
2.class # Fixnum:Herc, number 2is the Fixnun.
conside
float class.
3.8.class # Float: Here, floating point numbers include Exam
the singleton instance TrueClass.
true.class #TrueClass : Here, truc isconsidered as
falsc.class # > FalseClass
nil.class # NilClass
2. Iteratorsand Blocks
code which is enclosed in curly braces is
In ruby, Iterator is the special type of method which acts like a loop whercas, the loop. The most commonly used iterator name

called "block". This block is related to the method invocation and acts like the body of a
is "each".
array or hash. It will return allthe elements
each: TThis iterator executes the block of codecontained in it lor every element of-the example 1.
of the arrayor hash. Array class dofines an "each" iterator which can be cxplained by using the
5.
Example-1
literal.
array =[4, 3, 2, 1]# This linc represents an array
6
arravl4l~aray[3] - 1 #This.linerepresents that square brackets can be used to query and set the elements of an aray
avench doelt # Here, 'each' is an iterator and block contains a parameter called "elt".
"54321" 7.
print clt + I # T'his line prints
end# This line represents that block Is delimited with dolend rather than curly braces (1 )
hash
class also defines an 'each'
Similar to array class, hashkey/value pair can be invoked iterator-which is explained with the help of example- In 8
by the iterator method and both key passedas
class, the block of code for
cach and value can be
blocks.
parameters to the
of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
WARNING: Xerox/Photocopying
UNIT-1 Introduction
1.5
Example-2
h= { # Here, hash will map number names to digits.
: two =2
# "arrows" represent mappings (key ’
three 4
value)
# colons represent symbol
literals.
h[:two] #’2value can be accessed by using key.
h[:four] = 4 # new |key, valuel pair can be added to the hash.
h.each do |key, -aluel # Iterate via |key,
valuel pair
print "#{value}: {key}; # variables can be substituted in the
end
string.
# Prints: "2: two;3: three; 4: four;
Array and hash make,ise of square brackets [ ]to query and to set the values
available in both of them.
3. Expressions and Operators
In ruby, Syntax is expression-oriented which means that allstatements and
as expressions. This is because, statements will not return controlstructures (like if-else) are considered
value.
significant yalues but method definitions and while loops return the nil

In ruby, operators can be implemented as methods but these methods are


their requirements. The follow ing are the few examples of defined (or redefined) by classes according to
ruby operators.
1 max =a>b? a:b # This is a conditional operator
2. 2+3
#’5: addition
3. 2 *3
#6:multiplication
4 3**27 #3to the power 27 :Ruby possesses arbitrary size integers
5 2+3 ==5 #’ true :== tests equality
"Ruby" + "rails!" #’"Ruby rails!" :Concatenation of string
7. "Ruby!" *2 #"Ruby! Ruby!": Repetition of string
8. "%d %s"% [2 "rubies"] #"2 rubies" : style of Python and printf formatting.
4. Methods
In tuby, methods can be defined by using "def" keyword. So, the last expression value which is evaluated in the body is
considered as the return value of the method.
Example
def square(a) # Here, method name is 'square defined with one parameter 'a'.
a*a # It returns 'a' squared value.
end #It represents end of method.
Moreover, methods are also known as singleton methods because they can be defined on single objects by adding method
name with the object on which it is defined. However, example-l can be modified in the following manner.
def math.Square (a) # Here, method 'Square' is defined as a class method of math module.
a*a
end
5. Assignment (= Operator)
For answer refer Unit-I, Q12.
6. Regexp and Range
For answer refer Unit-I, Q13(i).
7 Punctuation Suffixes and Prefixes
For answer refer Unit-I, Q13(i).
8. Classes and Modules
Eor answer refer Unit-I, Q14.
SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS
1.6
SCRIPTINGLANGUAGES rJNTU-HYOERABADN
9. UNIT-1 Introduct
Ruby Surprises
The two surprising leatures of Ruby are as Q13. VWrite shor
follows, This is because
(a) An ruby, strings are mutable which surprising feature for Java programmers. operator. user can either
substrings using'U Rege:
append the character to a string by
can bc the
modify the characters ofa string or can delete, insert andreplace themethods can be defined by the string
<<" operator. Different
Moreover, which
user
class can Answer :
Can
(i)
(ii) Punc

modity the strings that are available using


at that place.
Javascript programmers, This is
(b) In Ruby, 'nil' value is considered as the
second : surprising feature for Cand
value is considered as false and other values are considered as true, However, "0' is
considered as false in Cbecausc,
and "i" (1)
Regexp an
In Ruby, R
string ( ") is considered as false in JavaScript. cmpty determine whethe
are available bety
Uses of Ruby
In Ruby,
Acommon use of ruby is rails.
[Ss]ia/
lt is available for all the computing platforms which are common. ld {4}/
3 The implementation of ruby is free. 1..4
4. lt is mostly used for writing the 1...4
servers.
It is used for experimenting with Thus, R
prototypes. The "=
6. It is also used to perform everyday 1
programming tasks. The "=
Q12. Discuss how assignments can be done in Ruby. 2.
sion ag
AnsWer :
(ii) Punctu
Assignment ( Operator) In Rub
In Ruby, values can be assigned to a variable by using" =" operator. methods whic
Example: a = z Example
In Ruby, assignment operator can be used along with different operators like+ and -. Metho
any element
Examples More
a += 1 #It increments value of a. pairs of meth
b-= 1 # It decrements value of b. an exclamati
whenever th
Ruby provides support to parallel assignments which means atleast one value and one variable is allowed in an assignment modifies the
expression.
Example
Examples Arra
a, b=2, 3 # It is similar to a =2; b=3
Pun
X, y = y, x # Here, the values of two variables are swapped. with @@,
a, b, c (2, 3, 4] # Elements of an array can be assigned to variables automatically. of Ruby.
Q14. Dis
In Ruby, methods are used to return atleast one value and parallel assignments can be used in combination with these
methods. Answer
Example Classes ar
A
def polar (a, b)
instance
theta Math.atan2 (b, a) # Calculates the angle
# Calculates the distance
Example
r=Math.hypot (a, b) T
[r, theta] # The last expression is considered as the return value
Ir
end number "
The below line represents the method used with parallel assignment.
distance, angle = polar (3, 3)
In Ruby, methods which end with =(Equals) sign are distinct. Since, these methods are allowed by rubythey can be
syntax.
invoked by using assignment variable
Example
0.a = (1) #Syntax of normal method invocation.
assignment.
0.a = 1 # Method invocation via
of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face
WARNING: Xerox/Photocopying LEGAL proceedings.
UNIT-1 Introduction 1.7
42 Write short notes on the following,
(0) Regexp and range
(ii) Punctuations,suffixes and prefixes.
Answer :

Regexp and Range


In Ruby, Regexp object refers to a regular expression object that determines textual pattern and
includes methods which
determine whether the given string will match a particular pattern or not. Moreover, Range shows the values
aneavailable between two end points. (1.e., integers) whicn
In Ruby, both Regexp and Range contain a literal
syntax shown below,
[Ss]ia/ #It matches "Sia" or "sia"
ld {4}/ #It matches 4
consecutive digits
1..4 #Allthe values of a where 1<a<4
1...4 # All the values of awhere
1<as4
Thus, Regexp and Range objects define the following
1. The "'= =" Operator (i.e., Normal) is used to test
operators.
equality.
2. The "=="operator is used to.test matèh and membership. Moreover. it can also be used to match case
statement expres
sion against each and every possible cases which occur. Thus, it is known as "case equality operator".
(ii) Punctuations, Suffixes and Prefixes
Ruby, methods can also be ended with the question mark (2) and exclamation mark (!). Here, the predicates (1.e., the
methods which return the boolean value) are marked by using a
question mark.
Example
Method named "empty?" defined by both array and hash classes can be used to test whether the data structure
any element or not. contains

pairs ofMoreover, the method name which ends with question mark (?) depicts that, the method should be used carefully. The
methods are defined by number of core ruby classes with similar names excluding the methods that end with and without
an exclamation mark. Generally, if a method dose not carry an exclamation mark then, altered copy of an
object will be returned
whenever the method is called. However, if a method carries an exclamation mark then it is known as mutator method
which
modifies the object present at a particular place.
Example
Array class defines sort and sort! methods.
Punctuation characters are prefixed with ruby variable names. For example, class, instance and global variables are prefixed
with (@@, @ and $. However, these prefixes define the scope of variable and are needed to disambiguate the flexible
grammar
of Ruby.
Q14. Discuss in brief about classes and modules in Ruby.
Answer :
Model Paper-l, Q2(b)
Classes and Modules
A class is defined as a group of similar methods which work on state of an'object. Here, objects state is
instance variables (i.e., variables whose names start with @ and whose values are different according to a associated with its
particular obiect).
Example
The following program determines the class named "sequence", operators and the way in which
iterator methods are written.
In this program, class indicates a series of numbers which are determined by three
parameters from, to and by. Where,
number 'a' inseries follows the below constraints.
# from Sa<to
#a= from + n * by, where n represents an integer
class Sequence # It is an enumerable class
include Enumerable #It inserts the method of this module in
"Sequence" class.
def initialize (from, to, by) #It initializes the newly created instances of the clss.
@ from, @to, @by = from, to, by # This line indicates instance variables in which parameters are saved
# later whenever required.
and can be used

SPECTRUM ALL-INONE JOURNAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES rJNTU-HDERABAN
1.8

def each
a = @rom
while as @o
yielda
at= aby
end
end

toW ines define the length method inorder to return the values in sequence.
def length
return 0 if @from>@to
integer ((@to- @from) |@by) + 1
end

# lhorder to provide random access to seguence. the array - access operator 1S oYe
def [ ] (index)
return nil if index <0
c=@from+index@by
if<< = @to

else
nil
end
end

# Inorder to return new Sequence objects,arithmetic operators are overridden


def * (fact)
Sequence.new( @from*fact, @to*fact, @by*fact)
end
def + (offset)
Sequence.new(@fromtofset, @to+offset, @by)
end
end
The sequence class is used by the following code,
S= Sequence.new (2, 11, 2) # It considers from 2 to 11 by 2's
s.each {la| print a} # This line prints "2 4 68 10"
print s[s.size - 1] #This line prints 10
t= (s+l)*2 # It considers from 6 to 24 by 6's.
In the above Sequence class, the main feature is the usage of "each"iterator. If focus is only on iterator method then it is
written in such a way that it accepts from, to and by parameters. However,-it is defined in a module ihstead of making the function
global.
module Sequences
def self.fromtoby(from, to, by)
a = from
whilé a<to
yield a
a += by
end
end
end
class can be writtena . .
Using Iterator method, the code of sequence 10i
line prints "2 468
Sequence. fromtoby(2, 11, 12) {la print a} # This
this book is aCRIMINAL act. Anyone found guilty is LIABLE to facaEGAL
WARNING: Xerox/Photocopying of proceedings.
UNIT-Yntroduction
046Give an overvlew of ralls. 1.9
Answer :
Rails is a highly
Antabase, web service andefficient/productive
web pagcs for
web application framework which
desired web software application, It wasprovides a default structure for
It widely iown as "Ruby on
Rails", lt mainly written in establishing the
ruby by David Heinemeier
are required to build a web application, uscs MVC (Model, Vicw, Controller) pattern to provide almost all the Hansson.
The sottware development process of tools that
These three environments are used to rails is divided into three cnvironments which are
Features of Rails perform various tasks for various
purposes.
developrnent, testing and production.
To increase
1.
produetivity, rails is equipped with many features as follows,
Meta Programming
Rails useS metaprogramming for writing
programs, where as other
A strategY to make programs to
handle other programs as inputframeworks use length coding for generating
data to utilize and modify progams.
metaprogramming.
Active Record automatically is called as
Rails introduced the concept of active
record framework to identify the columns in
automatically connected tó the desired domain obiect by
database schema so that they can be
using metaprogramming.
Convention Over Configuration
Other frameworks such as. Net, Java, etc
naming conventions to significantly reduce requires to write a lot of configuration code. Where as
the need of writing large ruby on rails recommenas
Scaffholding configuration code.
Sometimes developers have to create a temporary code (like a
are working. This technique is known as prototype) to observe how the major components of the code
code very quickly. scaffholding. This is used extensively by rails to create and view the temporary
5. Built-in Testing
Rails otfers as built-in testing tools such as
simple manner. It helps developers to extend Harnesses and Fixtures that makes the test cases to
and create simple automated tests.
write and execute in a
Installation of Ruby on Rails
Following software must be installed inorder to use rubyon rails.
1. Aweb server (eg: WEB rick, Apache, light
2.
TPD)
ADatabase system (eg: MySQL,
3.
SQLite, DB2)
Ruby
The rails Framework.
Steps to Install Rails on Windows
Stepl: Check the installed version of ruby by opening and typing the
following command in the command prompt.
ruby -v
If the displayed version number is at or above 2.2.2, then type
gem --version
A version number will be shown if ruby was
installed in the computer. Otherwise an error message will be appeared. If an
error is displayed, then goto step (2) and install latest version of ruby, orelse skip
Step2: Install ruby step (2) and continue from step (3)%/
Download the ruby installation package, rubyinstaller-2.2.2.x.exe from the website link,
with this package, ruby gems willalso be installed automatically. rubyinstaller-org, and install it. Along
Step3: Install rails
As Rubygems has been loaded, installing all of rails and its
the command line. dependent files can be done by typing the following command in
gem install rails
The above commnand will start the installation proceSS and takes
several minutes. Make sure that Internet is connected while
installing.
Step 4: Check rails version
rails - y
The above command willdisplay the following output if the rails is installed successfully
Rail4.2.4.

SPECTRUM ALLIN-ONE J0RNAL FOR ENGINEERING STUDENTS


LANGUAGES [UNTU.
1.10
Q16. VWrite a simple web application In ruby.
AnswerConsider
:
SCRIPTING
-HYDERABAD)
a web application which sends and receives emails. It has been developed using ruby on rails Rail is a weh
UNIT-1 Introducti
This templat
<htm>
application framework which provides a default structure for the database, web service and web pages. In addition.1o this it alsy <head>
a component of rails
Action rails
tacilitates web standards for data transfer, display standards, interfacing etc.ruby on rails are as follows. that allows <meta conte:

application to send as well as receive emails. Steps to send an email using sthe </head>
<body>
1. Creating Emails Project <hl>
the below command.
nittatly an email project has to be created. This can be done using <p>
tp> rails new testmail. </p>
</body>
The above command willcreate a framework required for further processis <html>
2.
Configuring Action Mailer Text part o
StepsforOpen
configuring action mailer
the environment.rb are asthefollows,
file from config folder of the emails project. Add the below given line at the end of this Welcome,
(i) Successful
file, <% = @us
config.action_mailer.delivery_method = : smtp 4, Calling th
(ii) Now add the below given block of code at the end of environment.rb, A simple
$bin/rails
config.action mailer.smtp_settings={ $ bin/rake
address: 'smtp.gmail.com', The actio
port : 587 user to mail for i
domain: 'xyz.com', class User
#POST/u:
user name: <username>',
#POST/u
password:'<password>', def create
authentication: 'plain', (@user =
enable startfis auto: true respond
if@user.
# Tell th
(ii) As apart of configuration, the hash value of SMTP server can bè changed with proper settings. The port number 25
and the authentication type need not be changed. The format of email can be changed from default to some other. UserMai
format.h
3. Generating the Mailer
A mailer can be generated using the below command, format.j:
else
tp >cd emails format.
emails> rails generate mailer testmailer. format.j
The above command will create a file with name testmailer.rb in applmailer directory. The contents of this file can be end
checked using the below command, end
class Emailer < ActionMailer: : Base end
end
end
Test the
Amethod can be created using the below given code,
http ://
class UserMailer <ApplicationMailer This w
default from: '[email protected]'
def welcome _email (user) New us

(@user = user Name

@url = 'http:/www.gmail.com Email

mail (to:@user.email, subject:'welcome to SIAGroup') Login

end Back
end The m
Nowcreate a fle with name·welcome.ntm.erb in app/views/user mailer/

WARNING: Xero/Photocopying of this book iS aGRIMINAL act. Anyone found guilty is LIABLE to face LEGAL Droceedings.
UNIT-1 ntroduction
1.11
This template will be used for email that is
<htm> formatted in HTML.
<head>
<meta content = text/html"; charset
<head> =UTF-8' http -equiv = Content -Type'/>
<body>
<hl> welcome <9% =
@user-name%><h1>
<p> Successfully signed in as <%= @user.login %> <br>
<body>
<html>
Text part of the application can be created as
Welcome, <% = @user.name %> follows,
Successfully signed in as,
<%[email protected] %>
4. Calling the Mailer
Asimple scaffhold is created as
S bin/rails generate
follows,
scaffold username email login
Sbin/rake db: migrate
The action mailer is being integrated with the active job for
user to mail for it. sending emails out request-response cycle by avoiding tne
class Userscontroller <ApplicationController
#POST/users
#POST/users.json
def create
@user = User.new(params [:user])
respond_todo format
[email protected]
# Tell the UserMailer to send a welcome email after save.
UserMailer.welcome _email@user).deliver later
format.html{redirect to@user, notice: 'User created successfully.')}
format.json {render json:@user, status ::created, location: @user}
else
format.html{render action :"hew'}
format.json {render json: @user :errors, status::unprocessable_entity}
end
end
end
end
Test the application now using the url given below,
http ://127.0.0.1: 3000/users/new
This will display the below screen using which the user can send the messages to any body.

New user

Name ]xyz
Email [email protected]

Login Tutorials
|Create user
Back

The message will be sent and a success message will be displayed on screen.

SPECTRUMALLIN-ONE JOURNAL FOR ENGINEERING STUDENTS


sCEIPTING LANGUAGES (JNTU-HYDERABAD)
1.12
Dueumnentation Comments
I.2 THE STRUCTUREANDEXECUTION Embedded APIdocumentation can also be included a8
OFRUBY PROGRAMS comments in a ruby program. Documentation comments should
Q17. Describe the lexical structure of aruby program. be written before module, class or method definitions. The rdo
Answer:
Model Paper-i, Q3(a) (Ruby Documentation) tool extracts these comments from a ruby
source and formats them like HTML or arrange them by usino
Lexical Structure
by the ri (ruby index) inorder to display. In general documentation
Aruby program is parsed as a sequence of tokens comments are mnultiline comments. So, they are written either
interpreter where, tokens consist of the following,
Comments using # character or = begin rdoc (this means without rdoc, the
1.
rdoc tool cannot process the comments).
Literals
2. Literals
Punctuations
Literals are values existing in the ruby source code which
ldentifiers
consist of the following,
Keywords Numbers
(i)
6. Whitespaces.
Comments
(ii) Regular expressions
1.

In Ruby, comments can be initiated using '# character and (ii) Strings
remain till end of the line. Here, Ruby interpreter neglects the (iv) Array and Hash values.
character and text after # but it does not neglect the newline Examples
character. This is because, the newline character is considered 100 # Integer literal
as a significant whitespace and can even act as a statement
terminator. Hundred/ # Regular expression literal
Moreover, if #character is found within a regular expres 'Hundred' # String literal.
sion or string, then it is not consider as a comment. 3. Punctuations
Example-1 Punctuation characters are used for writing ruby op
x+y= 10 # Sum of xand y is 10
erators.These characters can be used, for number of purposes
Comment including, delimitation of array, string, regular expressions,
Example-2 grouping and separating array indexes, method arguments and
s= "#SIA Publishers" # It is a string éxpressions.
Comment Examples
String
Multiline comments can be written in two ways. They are, * for multiplication
+ for addition
i) Most commonly used comments use # character at the
starting of every line. I| for boolean OR operation
Example 4. Identifiers
# Hello
Identifiers are the names given to the variables, classes
# This is SIA Publishers and methods. They contain numbers, letters and underscore
(ii) Another way to specify comment is to write in embed characters. However, they neither start with a number nor they
ded document style. Embedded document starts with a contain non-printing characters and white spaces. If they start
line beginning with "= begin" and ending on the line with a capital letter, then they are considered as constants and the
beginning with "= end". Allthe texts in between these interpreter willthrow warning whenever user wants to change
lines are identified as comments. The text from = begin value of a particular identifier. Moreover the names of classes
and = end need to be separated by atleast single white and modules must start with capital letters.
space. Example
Example X
= begin Hi! sial23
This is a comment section
sia publishers
= end
Embedded document doesn't work if the line doesn't From the above example, it can be inferred that, PI is
constant and identifier (i.e., sial23) can even begin with un
start with = (Equals sign). derscore.
WARNING: Xerox/Photocopying of this book ls a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.

4
UNIT-1 Introduction 1.13

(a)
Case-Sensitivity Moreover, three keywords are sinilar to tokens and can
In Ruby language, lower case and upper case letters are dif be treated in a special manner whencver they occur at the start
ferent because ruby language is a case-serDsitive language. ing of line.
Unicode Characters in Identifiers
(b) Ruby rules can be used to form identifiers which can Tokens
not be represented in the form of ASCII characters. begin cnd END
Generally, characters which are present outside of ASCII
character set and punctuation characters are considered The following table shows various methods which are
tobe valid in identifiers. used frequently.
Example
The below Ruby code is valid in UTF-8 encoded file. Methods
def a(a, b) #The method name is unicode catch throw at cxit

#multiplication include private attr


a * b #This is the body of method which lambda proc attr rcader
#multiplies its arguments loop protected attr wnter
end
load public attr accessor
(c) Punctuation Identifiers
Punctuation characters can appear at the require raise

ending of an identifier. The imeaning of eachbeginning


or
character is given in the below table, punctuation The following table shows various global funcions
which are used frequently.
Punctuation Meaning Global Functions
S(prefix) Itrepresents global variable
syscall exit! String
@(prefix) It represents instance variable
print system exec Integer
!(suffix) It represents an altemative to the original object
printf test eval Float
? (suffix) It returns Boolean value (or) a Boolean
valued method (Predicate) putc trap chop Array
-(suffix) It represents a method that is invoked by puts warn chop!
an assignment. rand open chomp!
readline load chomp
Examples
$Sia readlines iterator? calloc
@publisher scan gsub! caller
published? select gsub callcc
plan! split gets binding
time = sleep getc block given?
5. Keywords srand fork autoload?
In Ruby, there are few keywords that have special sprintf format autoload
meaning. Ruby parser treats these keywords in a special sub fail URI
manner. These include the following, sub! exit abort
Keywords The following table shows various objects which are
not then for end used frequently.
or true if break
redo undef in begin Objects
module taint freeze
rescue unless and new allocate
tainted? frozen?
Tetry until case alias nil? display
return when class END to _a id object_id dup
self to enum hash
while def BEGIN respond to? enum for
Super yield defined? FILE to _s inspect method eql?
nil üntaint is_a? methods
ensure else LINE_ equal?
next false elseif ENCODING superclass instance of? kind of? extend

Table: Keywords used in Ruby send inherited clone

sPECTRUM ALL-IN-ONE JOdRNAL FOR ENGINEERING STUDENTS


1.14 SCRIPTING LANGUAGES (JNTU-HYDERABADI
The above keywords are known as reserved words and Q19. Describe the syntactic structure of ruby.
they are not allowed to be used as identifiers. However, ruby Answer :
parser enables the usage of reserved words along with prefixes
(aa. @and Swhich can be used as class, instance and global In Ruby, the basie unit of syntax is the expression b
variable names. cause, the interpreter continuously evaluates the expressions
and retums the values.
6. Whitespaces
Primary Expressions
For answer refer Unit-I, Q18. Primary expressions are the basic expressions that show
Q18. Discuss about the importance of whitespaces the values directly.
in ruby.
Example
Answeer : Model Paper-l, Q2(a)
Numbers, String literals, Keywords like true, talse, selt,
nil and variable references.
Whitespaces
Rubv does notconsiders whitespaces, newlines and tabs Operators can be used to pertorm caleulations (op
as tokens. However, most of the whitespaces of the program are. erations) on values and for building compound expressions by
ignored, but stillimportant to understand them in few cases. combining various subexpressions with operators. However,
expressions are combined with Ruby keywords tor ereating
Whitespaces are used as statement terminators i.e., statement.
for indicating newlines. In ruby, semicolons can be used for
terminating statenments. However, semicolons are used only Example
when there are mnore than one statements in asame line. Ruby ifi>s then
interpreter detects the statement termination if the statement is
i =i-3
complete and has significant whitespaces after the statement.
end
It is important to note that whitespaces are used for styl
ing and to make the code neadable. In ruby, technically, the above statements are also con
Example-1 sidered expressions. But generally, user groups the expressions
and statements into parameterized units for executing them
a=b+c repeatedly and operating on varying inputs. These parameter
Example-2 ized units are called methods in ruby. So, the groups of methods
can be combined into classes and, modules are formed with the
a =b+c related classes while methods does not belong to these classes.
In example-1, the first line is incomplete, so the parsing Block Structure in Ruby
continues and the value 'a' is resultant sum of'b' and 'e'. In ex The programs in ruby follow block structures where,
ample 2, the first line is complete, so the value of "b' is assigned modules, classes, methods and statements comprising the blocks
to 'a' making the second line useless. of nested code.
In exceptional cases ofRuby 1.9, the interpreter considers The blocks in ruby programs can be written in two ways,
the line as continuing statement if the lines start with a period. (i) One way is to write by using curly braces with an inline
Relationship between Whitespaces and Method Invocations function. The code inside the braces are the block state
ments.
If there is white space after the method name, any ex
pression after the white space is used as method argument by Example
the interpreter. 2-times print "Sia Publishers"}
Example (ii) Another way is to write by using the keywords do and
end. This method is used when the block is written in
fla+b is difterent from f (a)+tb two or more lines.
To overcome this whitespace dependency, one has to Example
remember the folowing points,
[1, 2, 3].each do :
I. Use parentheses while invoking amethod, when the first print;
argument to amethod starts with open parenthesis.
end
2 Never use whitespace in between method name and
In order to avoid confusion, the body block can be called.
parenthesis.
A body can be defined as the list of statèments. Unlike blocks.
3. Make use of-w option while running the interpreter to bodies do not have curly braces or any keywords (do and end).
avoid the dependency. Blocks and bodies may be nested within one another.

WARNING: Xerox Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-1 Introduction
1.15
Example
module Sia
Class Books
def initialize (Ruby)
I0.foreach (Ruby) do |line!
if line [0, 1]== "#"
next
end
end
end
end
end
020, Write short notes on file structure of
ruby.
Answer :

Afile containing ruby code can be structured using the following rules (that are related' to thè
deployment).
1 A'shebang' comment (or acommand which tells the OS about execution) should be on the frst
liFe even if the ruby pro
gram includes any comment.
A 'coding comment should either be on the first or second line if.shebang comment is on the
first line.
3. A file has a line which contains the single token END without any whitespaces before or after, results in halting the
file process at a particular point. An arbitrary data which is readable by the program using I0 stream object DATAcan be
placed in the remainder of the file.
It is not mandatory to fit the ruby programs in a single file. Additional code from the exterFal libraries can be loaded/
imported using the keyword 'require'. (Require searches for particular modules of code against the search path., It also prevents
the module from being loaded multiple times).
Example
#! usr/bin/ruby - w # shebang comment
#-*-coding : utf- 8* # coding comment
require 'library name' #loading library
expressions # program code
statements

# End of the code program data.


Q21/ Write about the following,
() Program Encoding
(i) Program Execution.
Answer :
(i) Program Encoding
ARuby program is considered as a series of characters. These characters are ASCIl characters and are used by Ruby to
write all its kevwords., Here, each operator and punctuation are drawn from this ASCII character set only. However, Ruby inter
preter suppose that source code of ruby is encoded in ASCII by default.
InASCI encoded files, strings can have arbitrary bytes that consist of characters which display only non-printing control
characters. So, ifUTF-8 encoding is used for writing afile then, regular expression, commas and strings can have arbitrary unicode
characters on, If.Japanese SJIS or EVC encodings are used for encoding afile then strings can have Kanji characters only.
Specifying Program Encoding
In Ruiby 1.8.different encodings can be specified by using-Kcommand-line option. Here, -Ku option is used for invoking
the interpreter which contains unicode characters encoded in UTF-8 inorder to run the program. Thus, programs which contain
either EUCor Japanese SJIS encodings might run by making use of- Ks and- Ke options.
In Ruby 1.9. special comment (i.e., "coding comment") can be specified at the starting of file by the author of that script.
Example: #coding : utf-8
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
1.16
sCRIPTING LANGUAGES [JNTU-HYDERABAD
are as follows,
There are two users that make use of coding comment which
following manner.
() Emacs uscrs can write the encoding comment in the
coding : utf- 8
Viusers can write the encodiug comment in the
following munner.
()
#i: set tilecneoding utt 8:
first line is not ashebang comment.
The above cnooding comments can be validated on the starting line of afile iff
Example
! s bnuby w# This line represents shebang comment
# n g : ut-S #This line represents encoding comment which willcome in second line ifffirst line is a shebang comment
Edng names can be written in lowercase, uppercase or a mixture of both because they are not case-sensitive. Thue
Ruby 1. rovides support to the source encodings which are follows,
The Unicode encoding (i.e., UTF-8)
US-ASCIl(i.e., 7 bit ASCII)
The Japanese encodings SHIFT_ JIS (i.e., SJIS)
4 ASCII-8BIT (i.e., Binary)
$. The European encodings ISO-8859-1 via ISO-8859-15
EUC-JP
When the three bytes of afile are 0XEF OXBB OXBF then, UTF-8 encoded files try to recognize their encodings. These
three bytes are considered as optional in UTF-8 and are called as the "Byte Order Mark" (BOM).
Thus, in Ruby 1.9 ENCODING (i.e., two underscores are present at the starting and ending) is a language keyword
that calculates the source encoding of presently executing code and results in ayalue which is an Encoding object.
2. Source, External and Internal Encodings
Source encoding explains the Ruby Interpreter about the way in which characters should be read from the seript as they
are usually set with the codingcomments. If aRuby program can have more than one file and each file can have different source
encodings then, source encoding of afile can alter the string literals encoding present in that particular file.
The externalencoding is used by Ruby by default whenever it reads from files and streams. This encoding is global to
Rubyprocess. Typically, this encoding is set depending upon the locale on which user's computer is arranged. However, user can
explicitly specify this epcoding with command line options.
The default internal encoding can be specifiedthe user making use of command line options. Thisis usually specified
when user choose to have alltext which is automatically transcoded to a single common encoding.The command line options
are as follows,
(i) -k- interpreter option This options is used to set the source encoding.
(iü) -and - - encoding option These options are usedtoset both encodings (i.e., default external and default internal encod
ings) for specifying an encoding using its full name instead of on-character abbreviation.
(iii) -U(i.e., for unicode) This option indicates a default internal encoding of UTF-8. So. shortest for this option is
-E: utf- 8.
Example
ruby - E utf-8 # This line represents default external encoding name which follows E.
ruby - E utf-8 # This line represents that space is optional.
ruby- E:sjis # This line represents default encoding only.
ruby-E utf-8: binary #This line represents external and internal encodings.
ruby - endocing utf-8 # This line represents that -encoding is only like - E.
ruby --encoding = utf-8 #This line represents that anequal sign can even be used with -encoding.
Encoding.default external and Encoding.default_internal encodings are used by the user to query these encodings (i.c..
default external and default internal).
Here encoding object is returned by theabove class methods. Moreover, encoding locale charmap is a method used to
ohain the names(Iikeastring) of character encoding which is derived override
from the the
locale. However, this method constantly depends
default external encoding.
on the setting of locale and neglects thecommand line options which
WARNING: Xerox/Pholocopying of.this book is aCRMINAL act. Anyone found gity is LIABLE to fce LEGAL proceedings.
UNIT-1 introduction
1.17
Program Execution
Ruby language is a scripting language which means its programs are scripts or does not have-any
lists of
main function and it executes the program code line by line except for the control statements. statements.
The ruby interpreler checks for
BEGIN Statements first and executes the code within its body. Then, it starts executing the code
from first line.
If the rutby interpreter finds a class definition then, it executes the class and
the interpreter encounters the method inyocation expression and executes it for the
defines a new class respectively. Afterwards,
mnethod. This inturn executes the statements
available in the method body.
L3 PACKAGE MANAGEMENTWITH RUBYGEMS
Q22. Write about RubyGerns in brief.
Answer :
Model Paper-l1, Q2(b)
RubyGems is defined as a standardid package. insiallation framework for libraties and applications which facilitate the
users and developers with the following,
1 Astandardized package format.
2 Acentral repository for hosting packages in the
sane forinat.
3. Installation and management of multiple, bnultaneously installed versions of the same library
4 End-user tools for querying, manipulating, installing, uninsta!ing packages.
To install a new library before RubyGems, a packape as to be sea.ched on web, downioaded and
installed to find the
dependencies. After the RubyGéms came in to picture, it duS Cverything as desired. !evelopers wrap their
libraries intosingle files called gems which follow a standardizcd format, The RubyGen1s system provides a applications and
for,maripulating these gemfiles. command-line tool
Q28. How RubyGems and application germs are installed?
Answer:
Steps to Install RubyGems
1. Go to project's home page at
http://rubygems.rubyforge.org.
2 Download RubyGems and unpack it.
3 Install it using the following script,
% cd rubygems-0.7.0
% ruby install.rb
This completes the installation procedure.
To test the installation, use the following script,
% gem help
There are few commands which are used for basic operations. They are,
gem -h/--help
gem -v/--version
gem command [arguments...] [options...]
Examples:
gem installrake
gem list --local
gem build package.gemspec
gem help install
Other commands that are used för any queries include the following,
8em help commands #lists all 'gem' commands
gem help examples #shows some examples of usage
gem help<COMMAND> #shows help on COMMAND (e.g. 'gem help install)
It should be noted that for each OS, the process of writing files into Ruby yaries.
SPECTRUMALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES [JNTU-HYDERABAD)
1.18

Installing Application Gems (http://rake.rubyforge.org) is the f..


to installan application writtenin ruby. Jim Weirich's Rake
RubyGems can be used to build Gems.
application as a gem. Also, Rake has the capability
#Locating and installing Rake with RubyGems
"o gem install -r rake #nstalls Rake

Output
Attempting remote installation of 'Rake'
Successfully installed rake, version 0.4.3
#Provides the installed Rake version

Output
rake, vesion 0,4.3
specified with version requirement operator
if the uNer desires to work on older versions, it can be
"gem install -r rake -y "< 0.4.3" #The user requires version less than 0.4.3
Output
Attempting remote installation of 'rake'
Successfully installed rake, version 0.4.2
rake --version #Produces the version installed

Output
rake, version 0.4.2
argument which specifies
The method require gem a¡nd the attribute add dependency in a Gem::Specification accept an
operator major.minor.patch level.
aversion dependency. These version dependencies are of the form
The version operators are as follows,
Operator Functionality
The version must be exact as specified (Major, minor and patch level should also match)
The version can be any, except the specified one.
The version must be greater than the specified one.
The version must be less than the specifièd one.
The version must be greater than or equal to the specified one.
The version,must be less than or equal to the specified one.
The Version must be greater than or equal to the specified one and less than the specified version after having
its minor version number increased by one(This is to avoid API incompatibilities between minor version
releases). This is known as boxed version.
RubyGems downloads the rake package along with its libraries, command line program rake and installs it since rake is
an application.
Gem program can be controlled by subcommands. Each Subcommand has its own options and help screen.
Example
-r:To operate remotely
-! :To operate locally
Despiteof RubyGems keeps separate versions of the application's library files while installing different versions of the
same application, it doesn't run the application with appropriate command. It just overwrites the previous application. To over
come thís. -t opion is added to the Rby Gems install fail.
command. It causes RubyGems to run the gem's test suite and the installer
prompts toeither keep or discard the gem if the tests
% gem install UntestedProgram -t
Attempting local installation of 'UntestedProgram -1.0.1'
Successfully installed UntestedProgram, version 1.0.1
23 tests, 22 assertions, 0 failures, 1 errors...
keep Gem? [Y/n] n
Successfully uninstalled UntestedProgram version 1.0.1
The gem could be inspected to detect the cause of failure if the default option is chosen or the gem is installed.
WARNING: XeroxPholocopying of this book is a CRIMINAL act. Anyone'found guilty is LIABLE to face LEGAL proceedings.
UNIT-1 Introduction
1.19
024, How Gem libraries are installed and used?
Answer :
Model Paper-lli, Q2(a)
Installing and Using Gem Libraries
The best way to install a complete application is through
everything that user needs in a particular code. RubyGems. It also installs the required gem libraries and does
There are several templating packages available For beginners to work on
one of thoSe packages which are easy to operate. It is the an.application in HTML format. BlueCloth is
od write and convert the plain text to implementation of text to HTML conversion tool for web writers. It is
valid XHTML format.
Installation of BlueCloth gem.
% gem query -m Blue
REMOTE GEMS ***
BlueCloth (0.0.4, 0.0.3, 0.0.2)
# Three available versions of BlueCloth
#-n option to search the central gem repository for any gem
matching with the expression
#Itinstalls the latest version by
default.
% gem install -r BlueCloth
Attempting remote installation of 'BlueCloth'
Successfully installed BlueCloth, version 0.0,4
Generating API Documentation
Towork with BlueCloth, API documentation has to be
generated. This is
mand. Then, RubyGems will generate RDoc documentation for the gem it is done by adding --rdoc option to the install com
currently installing.
#Installation
% gem install -r BlueCloth --rdoc
Attempting remote installation of'BlueCloth'
Successfully installed BlueCloth, version 0.0.4
Installing RDoc documentation for BlueCloth-0.0.4..
WARNING: Generating RDoc on .gem that may not have RDoc.
bluecloth.rb: cc
Generating HTML
There are two options to view this HTML documentation. They are,
1. The RubyGems documentation directory can be opened directly and documentation can be
of each gem's documentation'varies from system to system and by the browsed. The storage location
memory
the documentation for each gem is stored in a central, protected, RubyGems chosen to install the gems. In most cases,
documents is to get its main directory location through gem command.
particular space. The best way to detect these
Example
%gem environment gemdir
husr/local/1ib/ruby/gems/1.8 # Path
RubyGems stores generated documentation in the doc/ subdirectory of this directory. It is stored in the specified
it can be viewed by opening the file index.html. A
shortcut can also be created for better usage. path and
Ashortcut on Mac OS X boxes is created as follows,
%gemdoc='gem environment gemdir /doc
% ls Sgemdoc
BlueCloth-0.0.4
% open Sgemdoc/BlueCloth-0.0.4/rdoc/index.html
Sgemdoc must be declared in login shell's profile or rc file to save time.
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
1.20 sCRIPTING LANGUAGES [JNTU-HYDERABAD)
used. By de fauh
2 gem_serrver u i nlwus where gem_server starts a weh server running on the system that is being installation
it willstarts witti NISSOS. I: iso serves gems snd cotesding documentation from the default RubyGems
directory.
# To start gem_serr
% gem_server
[2004-07-18 11:28:S1) INFO WEBrick 1.3.1
(2004-07-18 11:28:S1] INFO ruby 1.8.2 (204-06-29)[i386-mswin32)
(2004-07-18 11:28:S1) INFO WEBrick:.HTTPSenerstart: port-8808
The tollowing command line options are usd 1or ovctnding :
-p:For overriding the port
-d:For ovemiding the gem directory
After the gem server program is starled, the documentation can be accessed to any of the installed gems by pointing the
web browser to htp:localhost:8S08 on local computer. It shows the list of gems that are instatied with respective deseriptions
and linkS o theirRDoc documentation.
a25. What are t.o basics for writing a code inBlueCioth? Fxplain indetail.
Answer :

RubyGems arc used to download the lihrary and to load its components into the application. Before Ruby Gems, BlueCloth
is directly used by the inilowing command.
require "bluecloti:
In RubyGems, require is replaced with require_gem.
Example
require 'rubygems'
require gem 'BlueCloth', "=0.0.4"
doc = BlueCloth::new << MARKUP
Hello World [text][1].
Welcome [BlueCloth)[1).
Testing.
[1]: http:/ruby-lang.org
MARKUP
puts doc.to html
Output
<p>Hello World <a href-http://uby-lang.org'>text</a>, Welcome <a href- "http://uby-lung,on:"BlueClothrdaTesting. <p
Code Explanation
The first two lines in theexample program are the RubyGems specific code, 'The first line loads the RubyGems core librar
ies that are necessary to work with installed gems. The second line adds the BlucCoth gem to Rutby's $LOAD PATH, It uses
'require' to load any libraries that are specified by the user to be autoloaded. First, the goms library moditics your $LOAD PATH,
including any directories you have added to the gemspec's require_paths. Second, it oalla Ruby'% rcquire mcthod on any files
Specified in the gemspec's autorequires attribute. Its this $LOAD_PATH modifying behavior that cnables RubyGems to manage
multiple installed versions of the same library
Each gem is a bundle of resources and may contain everything in one or more library filo, Before RubyGcms, the files
are copiedto Ruby's predefined load path i.e. to the shared location in the Ruby library tree, But, RubyGems doesn't follow this
nrocedure: It stores the version of each gem in its own directory tree and is not included with atandard Ruby library dircetories.
Thus, it is the RubyGenms responsibility to reach out these files by adding the gem's dircctory (iee to Ruby' load path.
In Bluecloth, the templating code is stored in one file namely bluecloth.rb which is loaded by the roquire gcm, The re
quire gem can specify a version requirement as its second argument(Optional).
In the above example, it is mentioned as (require gem'BlueCloth', ">= 0.0,4"), which mcana 0.0.4 or gicater should be
inetalled to use thecode. The code fails if the user installs any other version which is notrequised tor the code.
WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LABLE to faca LEGAL proceedings.
UNIT1 Introdiction
1.21
o6 is. it necessary to always depend on
Answer :
RubyGems?,
Now-a-days, most of the programs afe
The code containing require `rubygems fails ifdependent
on RubyGcms though they are not the part of
it is distributod on the systems in which Ruby(Gems isstandard
not
ruby distribution.
must be installed separately after installing Ruby. installed. RubyGems
There ate two techniques toovercome this
issue. They are,
1. Wrapping the ruby gems specific code in a block and utilizing the ruby's exception
exception handler deals with the LoadError and passes the handling mechanism for output. The
code.
Example
begin
require 'rubygems'
require gem 'BlueCloth', ">= 0.0,4"
rescue LoadError
require "bluecloth'
end

Here, initially the code tries to get the rubygenms library. and invokes 'rescue LoadError' line if the trail fails. Then, the
BlueCloth is loaded. The require bluecloth fails, if the BlueCloth is not installed.
Installing a stub file while installing the gem. This stub file is added to the standard Ruby library
after the gem package contents. location and is named
Example
require 'bluecloth'
Instead of directly loading the BlueCloth, the stub is loaded which in turn calls the
require gem to load the correct package.
# Stub File

require 'rubygems'
$".delete(bluecloth.rb')
require gem 'BlueCloth'
The stub stores all the RubyGems specific code at one particular location so that the dependent
any RubyGems code in their source. The require gem call loads aH the library files that are libraries need not include
specified as autoloaded. Since the stub
installation was made default from the RubyGems 0.7.0 version, it's the user's responsibility to disable it with the
option. --n0-install-stub
Disadvantage
The RubyGems lose the capability to manage multiple installed versions of the same library using
version of a library, always include the LoadError method. stubs. To use a specific
Q27. Explain briefly the' process of creating òwn gems.
Answer :,
Model Paper-li, Q3(a)
The conventions. involved in creating own gems 'are as follows,
1 Place all the Rubý [oufce files in a lib/subdirectory. Later, add this directory tß
gem.
Ruby's $LOAD PATH While loading the
2. Add a fle which needs the require commands, for loading the whole project's
functionality to lib/yourprojct.rb. With or
without rubygems; this stép helpful for using the library and exploring the code.
3
Always include a README file which conains projeçt summary, author information,
for starting the gem. Follow RDoc format to add the copyright, license and the procedure
4
documentation generated during the gem installation.
Separate files should be maintained for each piece of code : tests in test/,
ditectories, This makes the. developers or any ofher users to understand the executable
gem.
scripts in bin/, source code in ext/
S
For better documentation purpose, store the Tiles in docs/
subdirectory of gem 'add refer the path location to users.
SPESTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS
1.22 sCRIPTING LANGUAGES [JNTU-HYDERABAD)
momlog!

lib/ tests/
README Rakeile bin docs/

momlog-server
momlog.rb momlog/

PhotoAlbumSetup.rdoc dairy.rb dbr.b Photo-album.rb


Installation.rdoc
Database Configuration.rdoc recipes.rb upload.rb rss.rb

ts-momlog.rb te-photo-album.rb tc-dairy.rb


tc-recipe.rb tc-upload.rb tc-rss.rb
After the files are properly laid out according to the usage, gem specification is done.
The Gem Specification
Agem specification is defined as a collection of metadata in Ruby or YAML which provides key information regarding
the particular gem. The gem specification is also known as gemspec and is considered as the heart of gem creation. The gemspec
is used as an input to the gem-building process. Allthe mechanisms that create a gem are conceptually same.
Example
require 'rubygems'
# Meta data can be held in an object
SPEC= Gem::Specification.new do x
# Basic INFO
X.name = "Sia"

X.version = "1.0.0"
X.author = "James"
x.email= "[email protected]"
x.homepage = "http://www.jamhost.com/Sia"
x.platform = Gem::Platform::RUBY
#Description
x.summary = "Study Materials for students"
# To generate the list and filtered out CVS and RDoc files
students = Dirglob(" {bin,docs, lib,tests}/**/*")
x.files = students.delete_if do litem|
item.include"CVS") || item.include?("rdoc")
end
x.require_path= "lib"
X.autorequire = "sia"
x.test file = "tests/ts sia.rb"
x.has rdoc = true

x.extra rdoc files ["README")


0.0.4")
x.add dependency("BlueCloth", ">=
end
LEGAL proceedings.
WARNNG: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face
UNIT-1 Introduction 1.23
028. How to deal with Ruby extension gems?
Answer :
Ruby Extension Gems
Several ruby ibraries are created as native extensions but not all gems are built with pure ruby code, there are two
ockage and distribute such libraries as gems. They are, ways

1. Distributing the gem insource format and allowing the installer to compile the code during the installation time.
2. Pre-comp1ling the extensions and distributing single gem to each separate platform inorder to provide support based on
the requirement.
Ruby gems provides an attribute called extensions for the source gems, which is an array of paths to ruby files. These ruby
sles generates Makefiles using mkmf library and are named extconf.rb, which is optional. Source files must be included in the
specification'ss files list to include them in the
gem package for distribution.
Example
require 'rubygems'
SPEC =Gem:Specification.new do <x
X.name = "Sia"
X.version = "1.0.0"
X.author = "James"
x.email = "[email protected]"
x.homepage = "http://www.jamhost.com/Sia"
x.platform = Gemn::Platform::RUBY
X.Summary ="ARuby wrapper for the MenuBuilderbooks database."
x.files = ["ext/main.c", "ext/extconf.rb"]
X.require path =""
X.autorequire = "MenuBuilder"
X.extensions = ["ext/extconf.rb"]
end
if $0 = FILE
Gem::manage gems
Gem::Builder.new(spec).build
end
RubyGems runs each and every extension programs and then executes the resultant Makefile after the source gem instal
lation is done.
Example
%gem install MenuBuilder-1.0.0.gem
Atempting local installation of MenuBuilder-1.0.0.gem'
ruby extconf.rb inst MenuBuilder-1.0.0,gem
creating Makefile
make
gcc -fPIC -g -02 -I. -Tusr/local/lib/ruby/1.8/i686-linux \ -usr/loca/lib/ruby/1.8/i686-linux-I. -c main.c gec -shared -LY
usr/local/lib" -o MenuBuilder.so main.o \ldl -lcrypt -Im -lc
make install
install -c -p m 0755 MenuBuilde.so\/usr/local/lib/ruby/gems/1.8/gems/MenuBuilder-1.0.0/. Successfully installed Me
nuBuilder, version 1.0.0
RubyGems cannot identify the system library dependencies of source gems. The gem installation fails ifthe system library
IS not installed. The consumer system needs a set of developing tools to accept the distributed source gems such as make program,
COmpiler etc. For example the windows users may not have these tools but the work can be done by distributing the precompiled
a Lnese precompiled gems can be created very easily.
sPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES [JNTU-HYDERABADI
1.24
Creation of Precompiled Gems
following steps,
Creation of precompile gens involves the
to the gemspec's files list.
I. Add the compiled shard object files
require path attributes. be accessible through reoni
Store all these files in one of the gem's $LOAD PATH and the shared objectwill
command modifies the Ruby's
The rquire gem
call. it. The Gem::Specification class
defines constants fo
included as they are specific about can be
Platform attribute can also be
Ruby and for other platforms, the value of the RUBY PLATFORM variable
Window Intel Linux, Macintosh, pure
considered.
building the gem file.
Q29. Discuss the process of
Answer :
Building the Gem File
ways,
The gemn file can be created in the ollowing
ruby program.
1. Invoking the gemspec file which is runnable as a
Example
o ruby Sia.gemspec
Attempting to build gem spec 'Sia.genmspec'
Successfully built Ruby Gem
Name: Sia
V'ersion: 0.0.7
File: Sia-0.0.7.gem
2. Using the gem build command.
Example
% gem build Sia.gemspec
Atempting to build gem spec 'Sia.gemspec
Successfully built RubyGem
Name: Sia
Version: 0.0.7
File: Sia-0.0.7-gem
The created gem file can be distributed to any of the ruby users through FTP.
website, server or email. The receiver has to
follow certain commands to install' the gem. They are as follows :
% gem install Sia-0.0.7.gem
Attempting local installation of 'Sia-0.0.7.gem'
Successfully installed Sia, version 0.0.7
These gems can also be added to ruby community through RubyForge, http://rubyforge.org which is an open source project
managetment web site that hosts the central gem repository. This RubyForge's release feature keeps on adding it to the repository.
The users can install it easily and can access it through RubyGems' remnote query.
Q30. How to build gems with rake?
Answer :

Gems can also be created using Rake, which uses the Rakefile command to control the process. It defines a set of rules
and tasks in the ruby syntax. Rake documentation states that tasks are the main unit of work in aRakefile which contains a name,
prerequisites, and alist of actions. In general, rake's built in task method can be used to define the named tasks of Rakefile. In
some cases like gem creation, helper code is provided to automate and ignore the repetition of work. Rake contains atask library
called GemPackage Task which integrates gem creation into the other automated build and release process. In order to use the
GemPackageTask in Rakefile, the commands are as follows,
require 'rubygems'
Gem::manage gems
require 'rake'gempackagetask'
spec - Gem::Specification.new do /x
X.name = "Sia"
X.version = "0.0.7"

WARNING: XerowPhotocopyíng of this book is a CRIMINAL act Anyone found guilty is LIABLE 0face LEGAL proceedings.
UNIT-1 Introduction 1.25

X.author = "James"
X.email = "}[email protected]"
x.homepage = "http://www.jamhost.com/Sia"
X.platform = Gem::Platform:RUBY
x.summary = "Study materials for students"
x.files = FileList["{bin, tests, lib,docs}/a/"].exclude("rdoc").to_a
X.require path "lib"
X.autorequire ="sia"
X.test_file = "tests/ts sia.rb"
x.has rdoc = true
X.extra_rdoc_files = ["README"]
x.add _dependency("BlueCloth", ">= 0.0.4")
X.add_dependency("MenuBuilder", "s= 1.0.0")
end
Rake::GemPackageTask.new(spec) do lpkgl
pkg.need tar = true
end
Rake's FileList class is used instead of Dir.glob to build the list of fles as it is smarter than Dirglob and it automaticaly
ignores commonly unused files.
The basic syntax.of the identifier with. which the GemPackageTask generates a Rake target is as follows:
package_directory/gemname-gemversion.gem
For above example, its pkg/Sia -0.0.7,gem. This task can be invoked from the same directory in which Rakefile is stored.
Example
% rake pkg/Sia -0.0.7.gem
(in home/chad/download/gembook/code/Sia)
Successfully built RubyGem
Name: Sia
Version: 0.0.7.
File: Sia-0.0.7.gem
Once the task is invoked, it can be used for other rake tasks. However, this can be done by adding the dependencies to it
or vice versa. Example : Deployment or Release packaging.
I.4 RUBY AND WÈB:WRITING CGISCRIPTS, COOKIES, CHOICE OF WEBSERVERS,
SOAP AND WEBSERVICES
231. Howdo you write CGl scripts using Ruby?
Answer : Model Paper-1, Q3(b)
Writing CGI Seripts
One of the ways to implement web applications using ruby is by running the ruby program as CGI(Common Gateway
Interface) programs. It is easy to write CGI scripts using Tuby. The written script must be saved in CGI directory and marked as
executable. Then it can be accessed through browser,
#script
#/usr/bin/ruby
print "Content-type: text/htmlrnirin"
print "<html><body> WELCOME I's #{Time.now}</body></html>\rn"
Include the response header if browser doesn't add its headers automatically.
#script with response header
#!/usr/bin/ruby
print "HTTP/1.0 200 OK\rn"
print "Content-type: text/htmlrnrn"
print "<htm><body>WELCOME I's #{Time.now}</body></html>rn"
There are various options to write the code for request parsing, cookie manipulation, session management, output escaping
etc to make it easier for the users.
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERINGSTUDENTS
sCRIPTINGLANGUAGES [JNTU-HYDERABAD)
1.26

Using cgi.rb can be used.


manipulate forms, cookies, their environment and to manage stateful sessions etc., the CGIclass
To
Quoting as it willchange the whole meaning if it'squoted
When dealing with URLs or HTML codes, every character is important URL. Any / in the query portion of the URL is
meaning in a
wTOng. An example is aslash character (/)which has a special So, it must be escaped if it is not available in the
using it.
converted to the string o2F and must be converted again to a / for
pathnanme.
Space and ampersand are also special characters.
handle the special characters.
CGIofters the routines CGI.escape and CGI.unescape in order to
#Tocscape special characters
require 'cgi'
puts CGl.escape(" C/Java & Ruby")
Output
C%2FJava+%26+Ruby
#To Escape HTML special characters
require 'cgi'
puts CGI.escapeHTML("x > 1 && y< 1")
Output
x &gt: 1&amp;&amp: y &lt; 1
#Torestore the string, unescape method can be used
require 'cgi'
puts CGI.unescapeHTML("x &gt; 1&amp;&amp; y &lt; 1")
Output
X>1 && y<1
it in the method.
Based on the usage, the user can escape only particular HTML elements within the string by specifying
require 'cgi'
putsCGI.escapeElement(<hr><a href-"/mp3">Click Here</a><br>',', 'X)
Output
<hr>&It;a href-&quot; &gt; Click Here&lt;/a&gt;<br>
Here only the element 'X' is escaped.
Query Parameters
Query parameters are the parameters either påssed as part of URL or data embedded in the body of the HTTP requests.
They are hard to process as the value with given name might return the same request more than once.
Example
<html>
<head><title> Survey </title></head>
<body>
Students prefer Sia because:
<form target = "cgi-bin/survey.rb" >
<input type= "checkbox" name= reason" value= "Model Papers" >
It has model papers <br/>
<input type= checkbox" name= "reason" value= "Low price edition" >
It is less priced <br>
<input type= "checkbox" name= "reason" value= "Syllabus" >
Itcovers the whole syllabus <br/>
<p>
Your name : <input type= "text" name "name">
</p>
<inputtype= "Submit"/s
</form>
</body>
</htm>
WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-1 Introduction 1.27
Output

Sample CGIForm

Survey
D http:/Localhost/Survev.html Google
V Rendezvous vV Pop V Pragmatic Apple
Students prefer Sia because:
Model Papers
Low price edition
I Syllabus
Your name Arun

Submit

Students might choose more than one reason for choosing Sia. Class CGlallows the user to access the form data in a couple
of ways. First, by treating the CGlobject as ahash, indexing it with field names and returning ficld values.
require 'cgi
cgi = CGl.new
cgil'name']’ "xXXx"
cgi['reason'] ’ "Low price edition"
However, it does not work wellwith the reason field, it displays only one reason. To view all the reasons, the user can use
the CGI#params method. The value returned by params acts like a hash containing the request parameters. The user can read,
write and modify this hash. Each hash value is an array.
require 'cgi
cgi = CGI.new
cgi.params ’ {"name"=>["xxXx"], "reason"'=>["Model Papers", "Low price edition", "Syllabus"]}
cgi.params['name'] ["'xxxx"]cgi.params['reason'] ’ [("Model Papers", "Low price edition", "Syllabus")
cgi.params['name'] = [cgi['name'].upcase ]cgi.params -’ ("name"=>["xxXx*"],
"reason" => ["Model Papers","Lowprice edition", "Syllabus") }
To check if particular parameter is present in a request, CGI#has key? Can be used.
require 'cgi'
cgi = CGI.new
cgi.has key?('namne') ’ true
cgi.has key?('age') false
Q32. Discuss in brief about generating HTML.
Answer : Model Paper-ll,Q3(b)
Generating HTML
CGI comprises of various methods that can be used to create HTML.The CGIobject must be created by calling CGI.new
so as to enable these methods.They also pass necessary HTML levels. These methods take code blocks (which return the string)
Tor their content, to make the nesting feasible.
Example
require 'cgi'
cgi= CGI.new("html3") # add HTML generation methods
cgi.out
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
1.28 sCRIPTING LANGUAGES [JNTU-HYDERABAD
cgi.html{
cgi.head ( "Mn"tcgi.title {"Test"}}+
cgi.body{ "n"+
cgi.form {"n"+
cgi.hr +
cgi.hl {"A Form"+"n"+
cgi.textarea("get _text") +"\n"+
cgi.br +
cgi.submit

Output
Content-Type: text/html
Content-Length: 302
<!DOCTYPE HTML PUBLIC -/IW3C//DTD HTML 3.2 Fina/EN"><HTML><HEAD>
<TITLE> Test <TITLE><HEAD><BODY>
<FORM METHOD= "post" ENCTYPE= "application/c-www-form-urlencoded">
<HR><H1> A
Form: <HI>
<TEXTAREA NAME= *get text" ROWS= 10" COLS= "80"></TEXTAREA>
<BR><INPUT TYPB= submit'></FORM></BODY><HTML>
The above code results in a HTML form titled Test'. This form also contains a horizontal line, a level one header, a text
input area and a submit button. CGIparameter, get text contains the text entered by the user when the submit button comes back.
The users doesn't really prefer this method, rather tends to write the HTML code - directly or utilizes
or frameworks.
templating systems
Q33. Discuss in detailabout templating systems.
Answer :
Templating Systems
Templating system distinguishes the presentation and logic of the application. It is believed that, the users who writes å web
application with ruby makes use of templating systems at some point in the process of completion. There are various
systems listed in different sources. The commonly used are RDoc templates, Amrita, and erb/eruby. templating
(a) RDoc Templates
The RDoc is used for generating the HTML and XML output present in it with a simple
system does not use conventional HTML and XML markup as expected, so it is difficult templating system. This templating
to edit those Rdoc template files with
the help of conventional tools.
Example
require rdoc/template'
HTML = %{Hello, %name.
<p>
The reasons are,
<ul>
START:reasons
<lib%reason name%:%rank
END:reasons
</ul>

WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL Proceedings.
1.29
UNIT-1 lnttoduction
data name' >'XXXX'.
'reasons' >|| reason name' Model Papers, rank' '100 }.
{'reason name'>Low Price Fdition', 'rank'0'),
'reason name' Syllabus', 'rank'>'99},

t=TemplatePage.new(HTML)
t.write_html on(STDOUT, dutu)
Output
Hello, xXXX.
<p>
The reasons are,
<ul>
<li>Model Papers: 100
<li>Low Price Edition : 110
<li>Syllabus : 99
</ul>
(b) Amrita
HTML cditors
Amrita S a library which generates HTML documents from a valid HTML template. So, it can use the
casily. Theretore, Amrita template displays freestanding HTML Dages accurately. It uses the id tags, inorder to find the values in
the HTML clements that are to be substituted. The HTML clenents are not included in the result and if the value corresponding
to a given name false or nil. Otherwise, it iterates the corresponding HTML elements when the value an array.

Example
require 'amrita/template'
include Amrita HTML =%{<p id-"greeting" >
<p> The reasons are : </p>
<ul>
<li id- "reasons"><span id ="reason_name'"></span> , <span id ="rank"></span>
</ul>

data ={
:greeting => 'Hello, xxxx',
:reasons =>
:reason name => Model Papers', :rank >'100',
{:reason name =>'Low Price Edition', :rank => '1 10'.
:reason name => 'Syllabus', :rank =>'99' }.

t=TemplateText.new(HTML)
t.prettyprint = true
t.expand(STDOUT, data)
Output
<p>Hello, XXXX</p>
<p> The reasons are : </p>
<ul>
<li>Model Papers: 100
<li>Low Price Edition : 110
<li>Syllabus : 99
</ul>
erb and eruby
Ruby can be embedded in an HTML document using various packages. These packages embed the ruby statements in the
form of documents into HTML page. This can be done by implementing eruby or erb which are part of eRuby. Embedding Ruby
in HTML is complex and functions more or less like JSP, ASP. or PHP
SPECTRMALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
1.30 sCRIPTING LANGUAGES (JNTU-HYDERABAD]
Q34. Write a short note on using erb.
Answer :
input
Ruby can be embedded into HTML by including an erb filter which doesn't allow the user to alter the data from the
nle. There are few exceptions which are as follows,
1. <%ruby code%>: It is used for executing the Ruby code in between the delimiters.
2. <%#ruby code%o>: It is used to ignore the Ruby code between the delimiters.
3. <%-ruby expression%>: It is used to evaluate the Ruby expression, and replace the sequence with the expression's value.
4. %line of ruby code: It is used to identify line that starts with a percent which is assumed to contain just Ruby code.
Erb is invoked as follows,
Syntax: erb [ options. ][document ]
When the document is not included, eruby willread from standard input. There are few command line options for erb.
They ae,
-d It sets SDEBUG to true
-n Itdisplays resulting Ruby seript with line numbers
-X It displays resulting Ruby script
It Loads the named library
-P It won't process erb on the lines starting %
-S It sets the safe level
-T It sets the trim mode
-V Itenables verbose mode
-Kkcode It specifies an alternate encoding system
Example
%i=1000 #Executes Ruby Statement
<%-i%> books
erb fl.erb
Output
1000 books
#The -n or -x are used for rewriting and executing the erb input as a Ruby script
erb -x fl.erb
Output
_erbout ="; i= 99
erbout.concat((i ).to s); erbout.concat "books...n"
erbout
Q35. Write an example code for embedding ruby into HTML.
Answer :
<DOCTYPE HTML PUBLIC /W3C/DTD HTML 4.01//EN">
htm>
<head>
<title>SIA </title>
<head>
<body>
<hl>Enumeration<hl>
<ul>
%5.times do la
<li>Book <%=a%></li>
oend
<Sul>
<hl> "Environment variables starting with T"</hl>
<table>

WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guity is LIABLE to face LEGAL proceedinas.
2 withfnstallingAnswer :Q36,
cookies
information.
parameter
Example Answer :Q37.
Cookies 3. 1

an
Explain Output Introduction
UNIT-1
Birectorylndex
DirectoryIndex
Write or ExampleTo listings The Then,Firstly, There The "Environment
TYPE TERM
PROGRAMEnumeration
TERM <html> </table>
<body> %end
%ENV.keys.grep{/^T).each |key|
do
else
Cookie.expirescookie end values.empty?
cgi.out("cookie" values
if l/ust/bin/ruby
CGI.newrequire
cgi ='cgi'cookie # thatCookies .rhtml
of check user ApacheEruby
application/x-httpd-eruby AddType
.rhtml the
msg msg = name
CGI arThesee
short application/x-httpd-eruby/egi-bin/eruby
for
Action Copythe arsufhX.
eruby e <tr><td><%=key%></td><td><%=ENV[key
cgi.cookies. associated are if can following few the
CGI::cookie.new "Last = "No = #out
cookies
directories
the Web in
='Sia defined notes directory
add stepsThen, Apacheprocess variables
= to index.html index.html server

Time.now updated new reference with or th e
two that
SPECTRUMcookie) [cookie_name] publishers'
updates"
are as
th e
on replace
that binary are web with of
handled
the cookies contains lines starting
+ was an storage indx.shtml index.shtml doesn't
th e
server
to eruby Installing
{msg} (cookie present must to be
ALL-IN-ONE *24* 1 # array
by Directorylndex
index.html the
followed iscan
values[0]} request. the of and have beconfigured
cgi-bin be
with
3600_name, of added
cookies ruby web /cgi-bin/index.rb configured eruby
sessions index.rhtml an T"
applications index.html.
directory. for
Time.now.to M¡reover, CGI nor to
J0URNAL using to in
or index.shtml directive httpd.conf. run to Apache.
only class. in |%></td></tr>
eruby the parse
one the So, state
ruby.
eruby
FOR s) which with Ruby
cookie. user the or on
on
INEERING can CGI the not, includes Apacheembedded the
alsO # user the created
cookies following web
set side. the documents.
back documents.
server.
index.rhtmland
STUDENTS method They
the directive
cookies are The
is It
used used produces Ruby
are
into allows embedded
byfor utilized
browser the
remembering the
Paper-ll,
Model
Q2(b) to
user appropriate
resuits.
create files
by to
setting
access directory are
session created 1.31
the the
SCRIPTING LANGUÁGES [JNTU-HYDERABAD]
1.32
Sessions
from the specific web browser. These sessions
Sessions are defined as the pieces of information that hold the requests
of cookies, but it produces effective results like higher-level
are handled by CGI:: Session class. Here, this class makes usesassociate
abstraction. The session's hash-like behaviour allows the user to values with keys. So, session can store most of its data
can even store its data in the memory, regular files.
on the server with the help of browser resident cookie. Moreover, sessions
pstore or any other private storage spaces.
It is important to note that,
1. Sessions must be closed after the usage for security purposes.
2. Sessions must be deleted after the complete usage.
Example
require 'cgi
require 'cgi/session'
cgi = CGI.new ("html3")
book =CGI : Session.new (cgi, "session key" ’"ruby web", "prefix ’ "web_session")
if book('lastaccess']
msg= "This book was accessed by # {book ['lastaccess']}"
else
msg = "No one is reading the book"
end
count (book'["'açcesscount]//0).to_i
count+=1
msg <<"<p> visit[, # {count}"
book ["accesscount"] = count
book ["lastaccess"]=Time.now.to s
book.close
cgi.out

cgi.html

cgi.body

msg

Q38. Discuss in brief about webservers used for ruby scripts and write a basic servlet program.
Answer :
Choice of Web Servers
In the past, Apache Web server is used for running the ruby scripts: But, at present WEBrick is being used for running
ruby scripts(Ruby 1.8). WEBrick is aflexible, pure-Ruby HTTP server toolkit and an extensible plug in-based framework usèd
for handling HTTP requests and responses.
The basic HTTP server that serves documents and directory indexes is as follows :
#!/usr/bin/ruby
require 'webrick'
include WEBrick
sery = HTTPServer.new (
:Port => 2000,
:DocumentRoot => File.join(Dir,pwd, "/htm)")

trap("INT") { serv.shutdown}
serv.start
WEBrick is not only for static content. It can be used as a Java servlet container too

WARNING: Xerox/Photocopying of this book is a GRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-1 Introduction
1.33
Servlet Program
The simple servlet program is as
follows,
#!/usr/bin/ruby
require 'webrick'
include WEBrick
hs =
HTTPServer.new( :Port => 2000 )
class HelloServlet <
def do HTTPServlet::AbstractServlet
GET(req, resp)
resp['Content-Type']="texthtm]"
resp.body=%{
<htm><body>
Calling from a #{req[User-Agent]}
<p>
Parameters: #{reg.query.keys.join(")}
<body></html>
end
end

hs.mount("hello", HelloServlet)
trap("INT"){ hs.shutdown
hs.start

#n the above program, do GETmethod is invoked based on the requests and response object used for displaying the data
and paramneters.
Qg9. Explain the concept of SOAP and Webservices.
Answer :
SOAP and Webservices
Ruby encourages SOAP implementation, which allows the user to write both servers and clients with the help of Web
services. SOAP is the easiest way of interconnecting with ruby applications written in other languages (C++, Java, Visual Basic)
because these applications doesn'i know the implementation language on which network peers are working. Within agiven net
work, SOAP applications can be operated locally and remotely.
SOAP (Simple Object Access Protocol)
SOAP is defined as the marshaling mechanism that uses XML for exchanging data among the two nodes given in anetwork.
It implements remote procedure calls, RPCs, between distributed processes. ASOAP server publishes at least one interface which
is defined on data types and methods that are used. Then these interfaces on the server are connected to local proxies created by
SOAP clients. If a method is called on the proxy, then it is passed to the corresponding interface on the server and the resultant
values on the server are passed back to the client through the proxy.
Example
class InterestCalc
attr reader : count
def initialize
@count =0
end
def compound(principal, rate, frequency, years)
@count t= 1
principal*(1.0 + rate/frequency)**(frequency*years)
end
end

SPECTRUM ALLIN-ONE JORNAL FOR ENGINEERING STUDENTS


Output
Output
1.34
If 2 2 count:
RNING: Count:
the years, client.rþ
0 ruby %Run I, 1, 1, server.rb
I, proxy.add_method('compound',
ruby %Run puts puts puts puts 'soap/rpc/driver' Code s.start
_method('count') trap('NT")
=#Client
proxy.add prOxyrequire s= end
'http://pragprog.com/InterestCale' NS
'InterestCale'
class require
'soap/rpe/standaloncServer #Server
=require Code
[2004-07-26T10:55:51.629451
years, 2 [2004-07-26T10:55:5
(2004-07-26T10:55:5
the [2004-07-26T10:55:5
run -- WEBrick
-- --Calc:
1.3.1 -- the
"count: "2
"2"count: Server.new('Calc',
end. init
defon
Server
compound
phasecompound client Calc: server years,years,
Calc: Calc:SOAP::RPC::Driver.new("http://localhost:
12321",
InterestCalc.new
_method(calc,
'count'add)
{ua_method(calc, calc =
tocopying is WEBrick::HTTPServer#start:
in ruby Start #{proxy. #{proxy.
compound s.shutdown <
in compound SOAP::RPC::StandaloneServer
another one
repeated monthly:
annually: 1.8.2 of
Calc. console
count}" count}"
1.639347.#12327]
window.(2004-07-26) 1.635 1.633755
NS,
again monthly:
annually: }
'0.0.0.0',
112.
of 715977620112.36 146 window
this
'compound,
then #12327] #12327] #12327] 'principal',
book #{proxy.compound(1000,
#{proxy.compound(1000,
it 12321)
displays
the (powerpc-darwin] for
is
a pid=12327 INFO INFO INFO INFO testing. 'principal,
CRIMINAL 'rate',
'frequency',
count
act. port=12321 rate',
Anyone as
4 "http:l/pragprog.com/lnterestCale")
0.06, 0.06, 'years') 'frequency,
since SCRIPTING
found
it 12, 1,
guilty reuses 2)}" 2)}" "years)
is the
LIABLE LANGUAGES
object.

to
face
LEGAL
rJNTU-HYDERABA

roceedings.
UNIT-1 Introduction 1.35
aA0, How does SOAP works while searching for a particular word in Google?
Answer:
The user needs a developer key for sending queries to the CJoogle, to get a developer key, there are few steps to be
They are,
Tolloweu
Go to http://www.google.com/apis
Create a Google account
3. Finally, a developer key sent from Google, once the process is done
Assume that the developer key is stored in the file .google key in home directory.
The Google API method 'doGoogleSearch' has ten parameters.
Parameter
Description
key Developer key
Query string
start Index of the first required result
maxResults The maximum number of results to return per query
filter Compresses results in order to avoid similar pages and pages from the same domain
restrict Restricts the search to a subset of the Google Web index
safeSearch Removes adult/explicit content from the results by enabling it
Restricts the search to documents in agiven set of languages
ie .Ignored (was input encoding)
Ignored (was output encoding)
The add methodcall can be used for constYucting a SOAP proxy for the doGoogleSearch' method.
Example
Aprogram for searching the results for "Sia Publishers" on Google and printing the first result.
require 'soap/rpc/driver'
require 'cgi'
endpoint = 'http://api.google.com/search/beta2'
namespace ='urn:GoogleSearch'
soap =SOAP::RPC::Driver.new(endpoint, namespace)
soap.add method('doGoogleSearch', 'key', 'q', 'start', 'maxResults', 'filter', restrict', 'safeSearch', 'Ir, "ie','oe')
query = 'Sia Publishers'
key = File.read(File.join(ENV[HOME'], "google_key")).chomp
result =soap.doGoogleSearch(key, query, 0, 1, false, nil, false, nil, nil, nil)
printf "Estimated number of results is %d. n", result.estimatedTotalResultsCount
printf "Query took %6f stconds.In", result.searchTime
first = result.resultElements[0]
puts first.title
puts first.URL
puts CGI.unescapeHTML(first.snippet)
Output
Estimated number of results is 63,50,000.
Query took 1.04 seconds.
The <b>Sia</b>Publishers
htp://www.siapublishers.com/
SIA Group, .a modern publishing company, Was initiated in the year 1979. We are the leading publishers and books
Distributor across the South India.

SPECTRUM ALLIN-ONE JOUREAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES [JNTU-HYDERABAD)
1.36

SOAP supports dynamic discovery of the interface of objects on the server using WSDL (Web Services Description Lan.
and access mechanisms for a web services interface
guage). A WSDL file is an XML document which defines the methods, types,
automatically.
SOAP clients can read WSDL files for creating the interfaces to a server
describing the Google interface. The search
The Web page http://api.google.com/GoogleSearch.wsdlcontains the WSDL
include the doGoogleSearch method explicitly.
application can be changed to read the WSDL, which removes the necessity to
require 'soap/wsdlDriver'
require 'cgi'
WSDL_URL = "http://api.google.com/GoogleSearch.wsdl"
soap = SOAP::WSDLDriverFactory.new(WSDL_URL).createDriver
query ='Sia Publishers
key = File.read(File.join(ENV['HOME), "-google_ key")).chomp
result = soap.doGoogleSearch(key, query, 0, 1, false, nil, false, nil, nil, nil)
printf "Estimated number of results is %d.\n", result.estimatedTotalResultsCount
printf "Query took %6f seconds.\n", result.searchTime
first = result.resultElements[0]
puts first.title puts first.URL
puts CGI.unescapeHTML(first.snippet)
Moreover, lan Macdonald's Google library (available in the RAA) is responsible for encapsulating the Web services API
which is behind a nice interface can also be used. This library has methods to build the date ranges and other restrictions on a
Google query. It also provides interfaces to the Google cache and the spell-checking facility.
#Code using lan Macdonald's Google library
require 'google'
require 'cgi'
key = File.read(File join(ENV[HOME] "google_key").chomp
google = Google::Search.new(key)
result = google.search(Sia Publishers')
printf "Estimated number of results is %d.n", result.estimatedTotalResultsCount
printf "Query took %6f seconds. n", result.searchTime
first =result.resultElements[0]
puts first. title
puts first.url
puts CGI.unescapeHTML(first.snippet)
T.5 RUBY Tk - SIMPLE Tk APPLICATION, WIDGETS, BINDING EVENTS, CANVAS,
SCROLLING
Discuss about Ruby Tk and write a simple Tk application.
Answer : Model Paper-lI, Q3(a)
Åruby application consists of various extensions like GTK, Fox ete which provide GUI (Graphical User Interface) to ruby.
Tk Extension

Tk-extension can be used by installing Tk on user's system and it works on both the systems i.e., Windows and Unix. To
experience the features of Tk from ruby, the user should have the complete knowledge abost it.
The user should follow certain steps to work with Tk. These steps are,
Step1:Create a container (likeTk Root or Tk Frame)
Step2:Create a widget (like labels or buttons)
Step3: Invoke Tk.mainloop when user is ready to begin the GUI.
WARNING: XerowPhotocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-1Introduction
1.37
Finally, the 1kengine gets the control of a program and shows widgets and functions according to
in the code. GUTevents specined

# load the tk extension module.


require 'tk'
# create a root level frame
root = TkRoot.new {title "Sia Publishers"!
# Making TkLa el widget as child of root frame
TkLabel.new (root) do
text 'Welcoine

pack {padx 20; pady 20; side 'left'}


# padding is done
end

# Enter into the main GUI event loop

Tk.mainloop
The above code can be simplified in the following
manner,
# Simplified code
require 'tk'
ii
TkLabel.new {text 'Welcome'; pack}
Tk.mainloop
Q42. Describe the concept of widgets in ruby.
Answer :

Widgets are quiet easy to create and inyolves addition' of Tk prior to the widget name in Tk documentation and used.
Afer adding 'Tk, the widgets become classes. For example, Label ’ TkLabel, Entry TkEntry, Button TkButton. Here, thé
keyword 'new' can be used to create an instance of the widget. So, if a parent is not specified for the particular widget then, by
default, it directs to the root-levelframe. However, the user can specify parent of aparticular widget; along with diferent options
such as size, colour, etc., based on their requirement.
When the program is in running phase, the user can retrieve the data from the widget by setting up callbacks and sharing
data,.

Setting Widget Options


In Tk reference manual, the options for widgets are listed by using a hypen. However, the options in peri/Tk can be passed
toawidget in a Hash, so, the same can be done in ruby to0. These options can also be passed using acode block, with name of
the option as method name inside the block and arguments to option can occur as arguments to method call. However, widgets
consider a parent as a first argument, followed by the code block of options (or hash of options).
Example
TkLabel.new (parent widget, 'text' ’ 'Hi!").pack (...)
It should be noted that,
1.
The block is evaluated with respect to the widget's object but not the caller's which means instance variables are not avail
able in the block. However, only local and global variables are available.
2
Distances (padx, pady) are represented in either of inch (i), millimeter (m), centimeter (c) and point (p), though they must
be pixels.
SPESTRUM ALL-N-ONE JoURNAL FOR ENGINEERING STUDENTS
1.38 SCRIPTING LANGUAGES [JNTU-HYDERABAD)
Getting Widget Data Setting/Getting Options Dynamically
Data can be retrieved from the widgets by making use A widget can be reconfigured in its running phase h
of the following. using the method 'configure'. It is similar to the new method
taking code block or a Hash.
(i) Callbacks and
(ii) Binding variables Example
It is easy to set up call backs by means of the conmmand require 'tk'
option which consumes a Proc object. This object is called if root = TkRoot.new {title "Sia"}
the callback fires. Here, kernel.lambda can also be used to cre
ate the Proc object (explicitly) though the proc is passed as the top = TkFrame.new(root) {relief 'raised'; border 10,
block related to method call.
lb = TkLabel.new(top) do
Example justify "left"
require 'tk'
text 'Hi!"
TkButton.new do
text "Back" pack ('padx' ’ 10, 'pady' > 10, 'side' 'bottom')
end
command {exit}
pack ('padx' ’ 5, 'pady' ’ 5, 'side' 'lef') TkButton.new (bottom)do
end text "Back"

Tk.mainloop command {exit}


Inorder to bind the ruby variable to a Tk widget's value, pack(padx' ’ 5,'pady' ’ 5,'side' ’ 'right')
TkVariable proxy can be used. This automatically updates the end
ruby variable if the widget's value changes. Thus, the widget
gives the new value, when the variable changes. TkButton.new (bottom) do
Example text "cancel"
require tk'
command {lb.configure ('text' ’ "Bye")}
packing ={padx' > 10,'pady'’ 10, 'side' ’'left"}
checked= TkVariable.new
pack ('padx'’ 5,'pady' ’ 5,'side' ’ 'left')
end
def checked.rank

value == "|"? "Yes":"No" bottom.pack (fill'’'both', 'side' 'bottom')


end Tk.mainloop
rank = TkLabel.new do The above program code changes the text from 'Hi' to
'Bye' when the 'cancel' button is clicked.
text checked.rank
cget: cget method is used to query widgets for the specific
pack (packing) option values.
end
Example
TkCheckButton.new do
require 'tk'
variable checked
bt = TkButton.new do
pack (packing)
end text "Back"

TkButton.new do justify "center"


text "Display Rank" border 10
command {rank. text (checked.rank)} end

.pack (packing) bt.cget ('text') ’ "Back"


end bt.cget (justify')> "center"
Tk.mainloop bt.cget ('border') ’ 10
WWAPNING: Xerox/Photocopying of this book Is a CRIMINAL act. Anyone found guilty is LIABLE tó face LEGAL proceedings.
UNIT-1Introduction
1.39
Write a ruby code for sample
Answer : application that performs pig latin translation.
#A pig Latin generator
require 'tk'
class PigBox
def pig (word)
cap = word = ^[A -Z]/
word.downcase!
result case word
when / ^[aeiouy]/
word + "way"
when/^ ((^ aeiouy]+ )X(*)/
$2 + $1 + "ay"
else
Word
end
cap? result.capitalize : result
end
def show _pig
@text.val [email protected] {lwl pig(w)}.join ("")
end
def initialize
p= {padx' ’ 5, 'pady' ’ 5}
root =TkRoot.new {title "Pig"}
top = TkFrame.new(root) {background "blue"}
TkLabel.new(top) {text 'Enter your text:'; pack(p)}
(@ text = TkVariable.new
TkEntry.new (top, 'textvar' ’ @text).pack(p)
pig_b= TkButton.new(top) {text 'Translate'; pack p}
pig b.command {show pig}
exit_b= TkButton.new(top) {text 'Exit'; pack p}
exit b.command {exit)
top.pack (AIl' » 'both', 'side' + 'top')
end
end
PigBox.new
. Tk.mainloop
The above code shows the genuine application of apig latin generator in which "Translate' button translates the typed text
X
(i.e., Ruby rails) into pig latin. This scenario is depicted in the below figure,
Pig

Enter your text

Ubyray alsray

Translate

Exit

SPECTRUM ALL-IN-NE JORNAL FOR ENGINEERING STUDENTS


1,407 sCRIPTING LANGUAGES (JNTU-HYDERABAD)
Q44./Describe the concept of binding events with example elq

Binding Events
widgets. With the help of widget's "bind'
The user either clicks, enters, moves over or generates events on the created
created.
method, the binding from an event on specific widget to the code block can be
Example
require 'tk'
imgl =TKPhotolmage.new {file "picl-gif"}
img2 =TkPhotolmage.new{file "pic2.gif"}
bt = TKButton.new (@root) do
image imgl
command {exit}
pack
end

bt.bind ("Enter") (bt.configure ('image' ’ img2)}


bt.bind("Leave"){bt.configure('image' imgl)}
Tk.main<oop
In the above program, two GIF image objects are created using "TKPhotolmage'. Then a buttot which displays first image
is created. Next, the Enter event is bindedto adapt the changes dynamically i.e., it displays the second image when the mouse
(cursor) is moved over the button. Moreover, the leave event displays the first image again when the mouse is not over (i.e., leaves)
the button.

Inorder to bind the named event passed as an argument, the following format consisting of substrings separated by dashes
can be used.

modifier-modifier-type-detail
modifier ’ Present in Tk reference (xample: Button-1, Conttol, Alt etc.)
type ’ Name of the event (Example: KeyPress, ButtonPress, Expose)
detail ’ Keysum for keyboard input or {1, 2, 3, 4, 5) (Example: 1, 2,3, 4, 5)
Example-1
When the control key is pressed then, the binding which is triggered on mouse release of bufton-2 can be stated as,
Control Button-2 ButtonRelease
(or)
Control ButtonRelease -2
The event may consist few fields like x, y positions and tim¹ ofan event. These items are passed by bind method to the
callback with the help of 'event field codes!.

Example-2
canvas.bind ("Motion", lambda {|x,yldo_motion (×, y)), "%x, %6y")
Parent Proc for the callback Event field string
The above method is used to obtain xand yco-ordinates based on the mouse movement. Iyytl;
WARNING:Xerox/Photocopyirig of this book is a CRIMINAL at. ANyohe found gulty is LIABLE 6tade tEGAL proceedings.
UNIT-1 Introduction
Whatiis canvas widget and
Q45.
1.41
give an example code for
AnSWer: basic canvas drawing.
Canvas

Canvas widget is provided by the Tk which is


used for drawing and producing
Example PostScript output.
require 'tk'
class Draw
def do press (x, y)
@begin X=X
@begin y=y
end
@present_line =TkPLine.new (@canvas, x, y, x, y)
def do motion (x, y)
if @present line

end
@present_line.coords @begin _x, @begin y, x, y
end
def do release (x, y)
if @present line
@present_line.coords @begin_ x, @begin y, x, y
@present_line.îll 'blue'
@present line = nil
end
end
def initialize (parent)
@canvas =TkCanvas.new (parent)
@canvas.pack
@begin x= @begin y= 0
@canvas.bind ("2", lambda {lel do _press (e.x, e.y)})
@canvas.bind ("B2-Motion", lambda {x, y| do_motion (x, y)}, "%x %y")
@canvas.bind ("ButtonRelease-2", lambda {}x, y| do_ release (x, y)}, "%x %y")
end
end
root = TkRoot.new {title 'Canvas'}
Draw.new(root)
Tk.mainloop
Output
Canyas

Explanation
The above çode can be used to draw straight lines by clicking and holding the button. This button will start drawing aline
Continuous till the mouse is moved and released.
SPESTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES [JNTU-HYDERABAD)
1.42
works.
Q48. Explain how scrolling Model Paper-ll, Q3(b)
Answer : comm)
when TkCanvas, TkText and TkListbox are set.. The
Scrollbar is required for scrolling purpose and can be used the widget's
bi-directional. This is because, moving a scrollbar must change
nication between a widget and scrollbar is always
scrollbar position.
view and changing the widget's view must change the
TkListbox and TkScrollbar are created. Then, scrollbar's callback
Inorder to achieve the functionality of scrollbar/scrolling,
of a list in y direction. The inverse association is made
of visible part
calls the yview method of list widget, which alters the value #set' can be used for setting the range in the scrollbar.
when the list obscerves that it needs to scroll. So, 'TKScrollbar

Example
require 'tk'
class Viewer

def initialize(filelist)
setup_viewer(filelist)
end
def run

Tk.mainloop
end
def setup_view (filelist)
@root = TkRoot.new {title 'scrolling list'}.
frame = TkFrame.new (@root)
img_w= TkPhotoImage.new
TkLabel.new (frame) do
img img_w
pack{'side' ’ 'r}
end

list w=TkListbox.new (frame) do


selectmode 'single'
pack {'side' ’ 'l}
end
list w.bind ("ButtonRelease-2")do
busy do
file name = list_w.get (*list w.curselection)
tmp = TkPhotolmage.new {file file name}
scale = tmp.height /120
scale = 1 if scale <1
img_w.copy (tmp, 'subsample'’ [scale, scale])
img_w.pack
end
end

filelist.each do |name
list w.insert ('end', name)
end

WARNING: Xerox/Photocopying of this book 0s a CRIMINAL act. Anyone found guity is


LIABLE to face LEGAL proceedings.
UNIT-1 Introduction
1.43
sh=TkScrollbar.new (frame) do
command {|*args|list_w.yview *args}
pack {'side > '1, 'fill' ’ 'y}
end

list
w.yscrollcommand {|first, last | sb.set (first, last)}
frame.pack
end

def busy
@root.cursor "watch"
yield
ensure

@ rOot.cursor " "


ènd

end

view = Viewer.new (Dir


View.run
["screenshots/images/*.image"])
Output

Scrolling List

Screenshots/images/9.image
Sereenshots/images/10.image
Screenshots/images/11.image.
Screenshots/images/12.image Seripting
Screenshots/image_/13.image Language
Screenshots/images/14.image Scroll
Screenshots/images/15.image Scroll Bar
Screenshots/images/16.image List
Screenshots/images/17.image def <=>
Screenshots/images/18.image Person =Array.new

Explanation
The above code shows few simple TKListbox manipulations which are as follows,
How to add elements to the given list.
2.
How tosetup acall back on releasing a mouse button.
3.
How to retrieve the current selection.

Moreover, TKPhotolmage can be used to zoom the images and to display difterent parts of the image

SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES [JNTU-HYDERABAD
1.44

IMPORTANT QUESTIONS

SHORT QUESTIONS Q14. VWrite short notes on cookies and sessions in


ruby.
Q1. llustrate the uses of ruby.
Ans: For answer refer Unit-1, 037. Important Question
Ans: For answer refer Unit-1, Q2. Important Quostlon
Q15. Explain the concept of SOAP and Webservices
Q2. What is meant by Ruby on Ralls?
Ans: For answer refer Unit-I, Q39. Important Question
Ans: For answer refer Unit-I, Q3. Important Questlon
Q16. Discuss about Ruby Tk and write a simple T
Q3. Define RubyGems. application.
Ans: For answer refer Unit-1,Q6. Important Question
Ans: For answer refer Unit-I, 041. Important Question

Q4. Define cookies in ruby. Q17. Describe the concept of binding events with
Ans: For answer refer Unit-I, Q9. Important Question example.
Q5. Write a short note on widgets. Ans: For answer refer Unit-I, Q44. Important Question

Ans: For answer refer Unit-I, Q10. Important Question Q18. Explain how scrolling works.
ESSAY QUESTIONS Ans:. For answer refer Unit-I, 046. Important Question

Q6. Explain in detail about Ruby.


Ans: For answer refer Unit-I, Q11. Important Question

Q7. Give an overview of rails.

Ans: For answer refer Unit-I, Q15. Important Question

Q8. Write about the following,


(i) Program Encoding
(ii) Program Execution.
Ans: For answer refer Unit-I, Q21. Important Question

Q9. How Ruby Gems and application gems are


installed?

Ans: For answer refer Unit-I,Q23. Important Question

Q10. Is it necessary to always depend on RubyGems?


Ans: For answer refer Unit-I,Q26. Important Question

Q11. How to deal with Ruby extension gems?


Ans: For answer refer Unit-I, 028. Important Questlon

Q12. How do you write CGI scripts using Ruby?.


Ans: For answer refer Unit-I, 031. Important Question

Q13. Explain the process of Installing eruby in


Apache.
036.
Ans: For answer refer Unit-I; Important Question

WARNING:Xerox/Photocopying of this book is a CRIMINAL act. Anyone found gullty is LIABLE to face LEGAL proceedings.

You might also like