Scripting Languages U-1
Scripting Languages U-1
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
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
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
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
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
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
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.
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
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
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/
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
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
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
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.
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
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,.
Ubyray alsray
Translate
Exit
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
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
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
filelist.each do |name
list w.insert ('end', name)
end
list
w.yscrollcommand {|first, last | sb.set (first, last)}
frame.pack
end
def busy
@root.cursor "watch"
yield
ensure
end
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
IMPORTANT QUESTIONS
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
WARNING:Xerox/Photocopying of this book is a CRIMINAL act. Anyone found gullty is LIABLE to face LEGAL proceedings.