[go: up one dir, main page]

0% found this document useful (0 votes)
11 views197 pages

Unit 1 Web

Uploaded by

karkaruchitha28
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)
11 views197 pages

Unit 1 Web

Uploaded by

karkaruchitha28
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/ 197

CS613PE SCRIPTING LANGUAGES

UNIT I
RUBY

Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is scripting language?
• Scripting language (also known as scripting, or
script) is a series of commands that are able
to be executed without the need for
compiling and is rather interpreted one by
one at runtime.
[Eg.] Ruby, Python, Java Script
Uses of scripting language
• Scripting language (also known as scripting, or
script) is a series of commands that are able
to be executed without the need for
compiling.
Characteristics of scripting language
• It is open-source, which means a user can have
full control to view and edit it.
• It is easy to learn and work with.
• Comparatively faster to develop than an actual
program.
• It has a limited number of data structures which
makes it easy to write and edit.
• The language is beneficial to bring interactivity in
web pages.
• It helps in creating new applications in web
browsers.
• It is used to create plug-ins and extensions.
Advantages of scripting language
• Easy learning: The user can learn to code in scripting
languages quickly, not much knowledge of web
technology is required.
• Fast editing: It is highly efficient with the limited
number of data structures and variables to use.
• Interactivity: It helps in adding visualization interfaces
and combinations in web pages. Modern web pages
demand the use of scripting languages. To create
enhanced web pages, fascinated visual description
which includes background and foreground colors and
so on.
• Functionality: There are different libraries which are
part of different scripting languages. They help in
creating new applications in web browsers and are
different from normal programming languages.
Disadvantages of scripting language
• It enables users to view the scripts.
• It need to install an interpreter or separate
program by the users before running the
script.
• Scripting languages may be slow in some
situations.
Applications of scripting language
• Scripting languages are used in web applications.
It is used in server side as well as client side.
Server side scripting languages are: JavaScript,
PHP, Perl etc. and client side scripting languages
are: JavaScript, AJAX, jQuery etc.
• Scripting languages are used in system
administration. For example: Shell, Perl, Python
scripts etc.
• It is used in Games application and Multimedia.
• It is used to create plugins and extensions for
existing applications.
Types of Scripting Language

• Server-side scripting language


• Client-side scripting language
Server-side scripting language
• A web server is where server-side scripting
languages are executed.
• When a client submits an HTTP request, the
server responds by delivering content.
Examples:
– ASP.NET
– Node.js
– Java
– Ruby
– Perl
– Python
Advantage
• Not visible to the general public
Client-side scripting language
• This executes on the client’s end—in their
web browser.
Examples:
– HTML
– CSS
– JavaScript
Advantage
• Reducing server demand, allowing web pages
to load quicker.
What is Ruby?
• Ruby is an open-source, object-oriented
scripting language.
• It was created in 1993 by Yukihiro Matsumoto
of Japan.
Why Ruby?
• Easy to learn
• Open source (very liberal license)
• Rich libraries
• Very easy to extend
• Truly object-oriented
• Less coding with fewer bugs
• Helpful community
Features of Ruby
• Ruby is an open-source and is freely available
on the Web, but it is subject to a license.
• Ruby is a general-purpose, interpreted
programming language.
• Ruby is a true object-oriented programming
language.
• Ruby is a server-side scripting language
similar to Python and PERL.
• Ruby can be used to write Common Gateway
Interface (CGI) scripts.
Features of Ruby
• Ruby can be embedded into Hypertext
Markup Language (HTML).
• Ruby has a clean and easy syntax that allows a
new developer to learn very quickly and easily.
• Ruby has similar syntax to that of many
programming languages such as C++ and Perl.
• Ruby is very much scalable and big programs
written in Ruby are easily maintainable.
• Ruby can be used for developing Internet and
intranet applications.
Features of Ruby
• Ruby can be installed in Windows and POSIX
environments.
• Ruby support many GUI tools such as Tcl/Tk,
GTK, and OpenGL.
• Ruby can easily be connected to DB2, MySQL,
Oracle, and Sybase.
• Ruby has a rich set of built-in functions, which
can be used directly into Ruby scripts.
What is Ruby Rails?
• An extremely productive web-application
framework.
• It was developed by David Heinemeier Hansson
under MIT License and is often just called “Rails”.
• You could develop a web application at least ten
times faster with Rails than you could with a
typical Java framework.
• It is an open source Ruby framework for
developing database-backed web applications.
• It can configure your code with Database Schema.
• No compilation phase required.
What is Ruby Rails?
• Rails is a framework used to create websites
using the general-purpose programming
language Ruby.
• It integrate Ruby with HTML, JavaScript and
CSS to manufacture a web application that
operates on a web server.
• It is generally considered to be a server-side
web application development platform.
What is Ruby Rails?

• It provides a structure to web developers for all


the codes.
• It is manufactured to ease web application
programming by predicting what every
developer needs to begin with.
• Rails requires less code but provides more
capabilities than any other language or
framework.
How Rails Works?
• If you run to a web browser to read this article;
the web browser blends three kinds of files;
HTML, CSS and JavaScript to display web pages.
A web server provides files to a web browser;
the web server can either be remote (
connected by the internet ) or on your
computer ( if you are into development ). HTML
is a language used to create an essential
combination of content and generic design
elements. CSS is a style sheet language used to
enhance the unique appearance of design
elements.
How Rails Works?
• JavaScript is a text-based programming language
used to add interactive features to the structures
created by HTML and CSS. A web server delivers
HTML, CSS and JavaScript either from static files or
an “application server”. Application servers make
dynamic files using programming languages such
as Ruby.
• A web application is a software program written in
Ruby and organized using Rails convention. Rails
amalgamates Ruby programming language with
HTML, CSS and JavaScript to create web
applications. To dynamically combine HTML, CSS
and JavaScript files from component files Rails uses
Ruby programming language.
Ruby Rails Architecture

• Rails is designed on the basic MVC architecture.


• MVC or Modal View Controller is a software
design pattern for developing web applications.
• It is made up of three parts –
– Modal: It is the lowest level of the pattern that is
responsible for maintaining data.
– View: It is accountable for displaying a portion of
or all data to the viewer.
– Controller: It is the software code that administers
interactions between Modal and View.
Ruby Rails Architecture

• MVC detaches the application logic from the


user interface layer and assists the separation
of concerns.
• The controller is the centre that receives the
requests for the application and then performs
with Modal to generate the required results
which are then in turn displayed by View.
What is Ruby on Rails used for?
• Ruby on Rails is best used for creating online
stores with decent and sophisticated browsing
and purchasing options.
• Ruby on Rails can also be used for creating
efficient stock marketing platforms.
• It is also beneficial to use Ruby on Rails to
create Social Networking sites.
• Ruby on Rails can be a good choice while
creating Non-standard complex projects.
• Due to Ruby on Rails’ easy building features
using it for creating Saas solutions is the
optimum choice.
Examples of Ruby on Rails
Benefits of Ruby on Rails
• Cost-effective: Ruby on Rails is a 100% free and open-source
framework. From a developer’s point of view, it is easy to use, and
with the add on advantage of tons of gems, the developer can save
plenty of time and effort.
• Secure: The framework is by default, installed and enabled with some
security measures. When you use Ruby in Rails, you are following a
secure development process.
• Flexibility: While creating web applications in Rails, it uses frontend
and backend abilities; these are simpler and easier to create. A single-
page web application uses Rails at the backend and maybe any other
framework like Angular for the front end. This makes the application
depend on Rails for the best qualities.
• Productivity: Employing Ruby to create your web application permits
you to develop features extremely fast. This happens because Ruby
effortlessly combines the 3rd party software libraries. It is amongst
the most productive programming languages.
• Consistent: Ruby on Rails helps keep a project organized and
decipherable as the developers have to follow standardized file
storage and programming conventions. Plus, it saves a lot of time.
CS613PE SCRIPTING LANGUAGES

UNIT I
The structure and
Execution of Ruby
Programs
Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
Structure of Ruby Programs
• The structure of Ruby programs is explained
as:
– Lexical Structure
– Syntactic Structure
– File Structure
– Program Encoding
– Program Execution
Lexical Structure
• The Ruby interpreter parses a program as a
sequence of tokens.
• Tokens include
– comments
– literals
– punctuation
– identifiers
– keywords
Comments
• A Ruby comment adds information to the
code that is helpful for the developers.
• Comments in Ruby begin with a # character
and continue to the end of the line.
• The Ruby interpreter ignores the # character
and any text that follows it.
Comments
• If a # character appears within a string or
regular expression literal, then it is simply
part of the string or regular expression and
does not introduce a comment.
[Eg.]
# This entire line is a comment
x = "#This is a string" # And this is a comment
y = /#This is a regular expression/ # Here's another comment
Comments Types

Comment Types

Single line Comment Multi line Comment

Embedded Documentation
Documents Comments
Single line comments

• Single-line comments allow description on


only one line at a time.
[Eg.]
# Addition of two numbers
Multiline comments

• Multiline comments are used for large text


descriptions of code and have more than one
line.
• Multiline comments also called as “block
comments”.
• Multiline comments are usually written simply by
beginning each line with a separate # character.
[Eg.]
#
# This class represents a Complex number
# Despite its name, it is not complex at all.
#
Style of Multiline comments

• There are two styles of Multiline comments.


– Embedded Documents
– Documentation comments
Embedded documents

• Embedded document starts on a line that


begins =begin and continue until a line that
begins =end.
• Any text that appears after =begin or =end is
part of the comment and is also ignored, but
that extra text must be separated from the
=begin and =end by at least one space.
• Embedded documents are a convenient way
to comment out long blocks of code without
prefixing each line with a # character.
Embedded documents - Example

=begin Someone needs to fix the broken code below!


Any code here is commented out
=end
Documentation Comments

• Ruby programs can include embedded API


documentation as specially formatted
comments that precede method, class, and
module definitions.
[Eg.]:
#
# The terms of a description list are bracketed:
# [item 1] This is a description of item 1
# [item 2] This is a description of item 2
#
Literals

• Literals are values that appear directly in Ruby


source code.
• They include
– numbers
– strings of text
– regular expressions
[Eg.]
1 # An integer literal
1.0 # A floating-point literal
'one' # A string literal
"two" # Another string literal
/three/ # A regular expression literal
Punctuation

• Ruby uses punctuation characters for a


number of purposes.
• Most Ruby operators are written using
punctuation characters, such as + for addition,
* for multiplication, and || for the Boolean
OR operation.
• Punctuation characters also serve to delimit
string, regular expression, array, and hash
literals, and to group and separate
expressions, method arguments, and array
indexes.
Identifiers

• An identifier is a name.
• Ruby uses identifiers to name variables,
methods, classes.
• Ruby identifiers consist of letters, numbers,
and underscore characters, but they may not
begin with a number.
• Identifiers may not include whitespace or
nonprinting characters or punctuation
characters.
Identifiers
• An identifier is a name.
• Identifiers that begin with a capital letter A–Z are
constants, and the Ruby interpreter will issue a
warning if you alter the value of such an
identifier.
• Class and module names must begin with initial
capital letters.
[Eg.]
i
x2
old_value
_internal # Identifiers may begin with underscores
PI # Constant
Case sensitivity

• Ruby is a case-sensitive language.


• Lowercase letters and uppercase letters are
distinct.
[Eg.]
• The keyword end is completely different from
the keyword END.
Unicode characters in identifiers

• Ruby is a case-sensitive language.


• Lowercase letters and uppercase letters are
distinct.
• The keyword end, for example, is completely
different from the keyword END.
• Unicode supports more than a million code
points, which are written with a "U" followed
by a plus sign and the number in hex;
[Eg.] The word "Hello" is written U+0048
U+0065 U+006C U+006C U+006F
Punctuation in identifiers
• Punctuation characters may appear at the start and end of Ruby
identifiers.
• $ Global variables are prefixed with a dollar sign. Ruby defines a
number of global variables that include other punctuation
characters, such as $_ and $-K.
• @ Instance variables are prefixed with a single at sign, and class
variables are prefixed with two at signs.
• ? As a helpful convention, methods that return Boolean values
often have names that end with a question mark.
• ! Method names may end with an exclamation point to indicate
that they should be used cautiously. This naming convention is
often to distinguish mutator methods that alter the object on
which they are invoked from variants that return a modified copy
of the original object.
• = Methods whose names end with an equals sign can be invoked
by placing the method name, without the equals sign, on the left
side of an assignment operator.
Example

$files # A global variable


@data # An instance variable
@@counter # A class variable
empty? # A Boolean-valued method or
predicate
sort! # An in-place alternative to the regular
sort method
timeout= # A method invoked by assignment
Keywords

• Keywords or Reserved words are the words in a


language that are used for some internal
process or represent some predefined actions.
• These words are therefore not allowed to use as
variable names or objects or as constants.
Syntactic Structure

• The basic unit of syntax in Ruby is the


expression.
• The Ruby interpreter evaluates expressions,
producing values.
• The simplest expressions are primary
expressions, which represent values directly.
• Other primary expressions include certain
keywords such as true, false, nil, and self.
• Variable references are also primary expressions;
they evaluate to the value of the variable.
Syntactic Structure

• Complex values can be written as compound


expressions
[1,2,3] # An Array literal
{1=>"one", 2=>"two"} # A Hash literal
1..3 # A Range literal
• Operators are used to perform computations on
values, and compound expressions are built by
combining simpler sub expressions with operators.
1 # A primary expression
x # Another primary expression
x=1 # An assignment expression
x=x+1 # An expression with two operators
Syntactic Structure

• Expressions can be combined with Ruby’s keywords


to create statements, such as the if statement for
conditionally executing code and the while
statement for repeatedly executing code:
if x < 10 then # If this expression is true
x=x+1 # Then execute this statement
end # Marks the end of the conditional
while x < 10 do # While this expression is true...
print x # Execute this statement
x=x+1 # Then execute this statement
end # Marks the end of the loop
Syntactic Structure

• Ruby is an object-oriented language, they are


called methods.
• Methods, along with related structures called
procs and lambdas.
• Finally, groups of methods that are designed to
interoperate can be combined into classes, and
groups of related classes and methods that are
independent of those classes can be organized
into modules.
Block Structure in Ruby

• Ruby programs have a block structure.


• Module, class, and method definitions, and
most of Ruby’s statements, include blocks of
nested code.
• These blocks are delimited by keywords or
punctuation and, by convention, are indented
two spaces relative to the delimiters.
Kinds of Blocks

Kinds of Blocks

Blocks Body
Block

• Blocks are the chunks of code associated with


or passed to iterator methods.
Syntax:
block_name {
statement1
statement2 .......... }
[Eg.] sample { print "Ruby! " }
• The curly braces and the code inside them are
the block associated with the iterator method
invocation sample.
Ways of declaring Blocks

Ways of declaring
Blocks

Inside the Inline between


do..end the curly
statement braces {}
Inside the do..end statement

• Blocks are the chunks of code associated with


or passed to iterator methods.
• do and end delimiters are usually used when
the block is written on more than one line.
Syntax:
block_name do
#statement-1
#statement-2 . .
End
Example

1.upto(10) do |x|
print x
End

Output:
1 2 3 4 5 6 7 8 9 10
Inline between the curly braces {}

• Formal blocks of this kind may be delimited


with curly braces.

Example:
3.times { print "Ruby! " }

Output:
Ruby! Ruby! Ruby!
Body

• A body is just the list of statements that


comprise the body of a class definition, a
method definition, a while loop, or whatever.
• Bodies are never delimited with curly braces in
Ruby—keywords usually serve as the delimiters
instead.
Example
module Stats # A module
class Dataset # A class in the module
def initialize(filename) # A method in the class
IO.foreach(filename) do |line| # A block in the
method
if line[0,1] == "#" # An if statement in the block
next # A simple statement in the if
end # End the if body
end # End the block
end # End the method body
end # End the class body
end # End the module body
File Structure
• First, if a Ruby program contains a “shebang”
comment, to tell the operating system how to
execute it, that comment must appear on the
first line.
• A shebang (#!) is a special kind of comment
that tells a Unix shell how to interpret this file.
• When you add this comment at the top of your
file, Ruby files are run as a executable
files, assuming they have the right
permissions to do that.
[Eg.] #!/usr/bin/env ruby
File Structure

• Second, if a Ruby program contains a “coding”


comment, that comment must appear on the
first line or on the second line if the first line is
a shebang.
• Third, if a file contains a line that consists of the
single token __END__ with no whitespace
before or after, then the Ruby interpreter stops
processing the file at that point.
• The remainder of the file may contain arbitrary
data that the program can read using the IO
stream object DATA.
Example

• #!/usr/bin/ruby -w shebang comment


• # -*- coding: utf-8 -*- coding comment
• require 'socket‘ load networking library
• ... program code goes here
• __END__ mark end of code
• ... program data goes here
Program Encoding –What is encoding?

• Encoding is the process of converting data into


a format required for a number of information
processing needs, including:
– Program execution
– Application data processing, such as file
conversion
Program Encoding

• At the lowest level, a Ruby program is simply a


sequence of characters.
• Ruby’s lexical rules are defined using characters
of the ASCII character set.
• Comments begin with the # character and
allowed whitespace characters are horizontal
tab, newline, vertical tab, form feed, carriage
return, and space.
• All Ruby keywords are written using ASCII
character.
Specifying Program Encoding

• Ruby interpreter assumes that Ruby source


code is encoded in ASCII.
• In Ruby, a different encoding with the -K
command-line option can be specified.
• To run a Ruby program that includes Unicode
characters encoded in UTF-8, invoke the
interpreter with the -Ku option.
• Programs that include Japanese characters in
EUC-JP or SJIS encodings can be run with the
-Ke and -Ks options.
Specifying Program Encoding

• The encoding of the script can be specified by


placing a special “coding comment” at the start
of the file.
[Eg]: # coding: utf-8
• The comments must include the string coding
followed by a colon or equals sign and the
name of the desired encoding.
Source Encoding

• The source encoding tells the Ruby interpreter


how to read characters in a script.
• Source encodings are typically set with coding
comments.
• A Ruby program may consist of more than one
file, and different files may have different
source encodings.
• The source encoding of a file affects the
encoding of the string literals in that file.
Default External Encoding

• The default external encoding is that Ruby uses


by default when reading from files and
streams.
• The default external encoding is global to the
Ruby process and does not change from file to
file.
• Normally, the default external encoding is set
based on the locale that your computer is
configured to.
• But you can also explicitly specify the default
external encoding with command-line options.
Encoding options

• Two new options, -E and --encoding, allow you


to specify an encoding by its full name rather
than by a one-character abbreviation.
[Eg.]:
ruby -E utf-8 # Encoding name follows -E
ruby -Eutf-8 # The space is optional
ruby --encoding utf-8 # Encoding following
--encoding with a space
ruby --encoding=utf-8 # Or use an equals sign
with --encoding
Program Execution

• Ruby is a scripting language. This means that


Ruby programs are simply lists, or scripts, of
statements to be executed.
• By default, these statements are executed
sequentially, in the order they appear.
• Ruby’s control structures alter this default
execution order and allow statements to be
executed conditionally or repeatedly.
Program Execution

• The Ruby interpreter is given a script of


statements to execute, and it begins executing
at the first line and continues to the last line.
• The Ruby interpreter first scans the file for
BEGIN statements, and executes the code in
their bodies.
• Then it goes back to line 1 and starts executing
sequentially.
• In Ruby, syntactic structures are statements like
any other.
Program Execution
• When the Ruby interpreter encounters a class
definition, it executes it, causing a new class to
come into existence.
• Similarly, when the Ruby interpreter encounters
a method definition, it executes it, causing a
new method to be defined.
• Later in the program, the interpreter will
probably encounter and execute a method
invocation expression for the method, and this
invocation will cause the statements in the
method body to be executed.
Program Execution
• The Ruby interpreter is invoked from the
command line and given a script to execute.
• The Ruby interpreter reads the file and executes
the script.
• It first executes any BEGIN blocks.
• Then it starts at the first line of the file and
continues until one of the following happens:
– It executes a statement that causes the Ruby
program to terminate.
– It reaches the end of the file.
– It reads a line that marks the logical end of the file
with the token __END__.
Program Execution
• Before it quits, the Ruby interpreter typically
executes the bodies of any END statements it
has encountered and any other “shutdown
hook” code registered with the at_exit function.
CS613PE SCRIPTING LANGUAGES

UNIT I
Package
Management with
RUBYGEMS
Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is Ruby Gems?
• RubyGems is a package manager for Ruby
libraries.
• RubyGems is used to deal with installation,
removal, updates of Ruby libraries.
• RubyGems libraries are called Gems for short.
Facilities in Ruby Gems
• It provides users and developers with four main
facilities.
– A standardized package format
– A central repository for hosting packages in this
format
– Installation and management of multiple,
simultaneously installed versions of the same
library
– End-user tools for querying, installing, uninstalling,
and otherwise manipulating these packages
Why Ruby Gems?

• It can drastically reduce development time of


projects as engineers don't have to write all
the features themselves.
Why Ruby Gems?

• It can drastically reduce development time of


projects as engineers don't have to write all
the features themselves.
Functions of Ruby Gems

• The functions of Ruby Gems is to manage


packages, this includes
– package creation
– package hosting
– package downloading
– package versioning
– package management in a project
Ruby Gems

• In the RubyGems world, developers bundle


their applications and libraries into single files
called gems.
• These files conform to a standardized format,
and the RubyGems system provides a
command-line tool, appropriately named gem,
for manipulating these gem files.
Installing RubyGems

• Download and install the RubyGems system


from http://rubygems.rubyforge.org.
• After downloading and unpacking the
distribution, install it using the installation
script given below.
% cd rubygems0.7.0
% ruby install.rb
Installing RubyGems

• To test that RubyGems was installed


successfully, the below command is used.
% gem help
Installing Application Gems
• Locating and installing Rake with RubyGems is
simple.
% gem install r rake
Attempting remote installation of 'Rake'
Successfully installed rake, version 0.4.3
% rake version
rake, version 0.4.3
• RubyGems downloads the Rake package and
installs it.
• Because Rake is an application, RubyGems
downloads both the Rake libraries and the
command-line program rake.
What is rake?
• Rake is a tool you can use with Ruby projects.
• It allows you to use ruby code to define "tasks"
that can be run in the command line.
• Rake can be downloaded and included in ruby
projects as a ruby gem.
• Once installed, you define tasks in a file named
"Rakefile" that you add to your project.
• Rack helps Ruby servers and frameworks work
together.
What is rake?
Installing Application Gems - older
version of Rake
• To install an older version of Rake, use
RubyGems’ version requirement operators to
specify criteria by which a version would be
selected.
% gem install r rake v "< 0.4.3"
Attempting remote installation of 'rake'
Successfully installed rake, version 0.4.2
% rake version
rake, version 0.4.2
Version requirement operators

Operator Description
= Exact version match. Major, minor, and patch level must be
identical.
!= Any version that is not the one specified.
> Any version that is greater (even at the patch level) than the one
specified.
< Any version that is less than the one specified.
>= Any version greater than or equal to the specified version.
<= Any version less than or equal to the specified version.
~> “Boxed” version operator. Version must be greater than or equal
to the specified version and less than the specified version after
having its minor version number increased by one.
Installing Application Gems - older
version of Rake
• During installation, you can also add the t
option to the RubyGems install command,
causing RubyGems to run the gem’s test suite
(if one has been created).
• If the tests fail, the installer will prompt you to
either keep or discard the gem.
% gem install SomePoorlyTestedProgram t
Attempting local installation of SomePoorly TestedProgram1.0.1'
Successfully installed SomePoorlyTestedProgram, version 1.0.1
23 tests, 22 assertions, 0 failures, 1 errors...keep Gem? [Y/n] n
Successfully uninstalled SomePoorlyTestedProgram version 1.0.1
What is test suite?
• Test suite is a collection of tests which can be
run.
Installing and Using Gem Libraries
• RubyGems is used to install Ruby libraries
• find and install the BlueCloth gem.
• % gem query rn Blue
*** REMOTE GEMS ***
BlueCloth (0.0.4, 0.0.3, 0.0.2)
BlueCloth is a Ruby implementation of Markdown, a texttoHTML
conversion tool for web writers. Markdown allows you to write using
an easytoread,
easytowrite
plain text format, then convert it
to structurally valid XHTML (or HTML).

• This invocation of the query command uses the n


option to search the central gem repository for any
gem whose name matches the regular expression
/Blue/. The results show that three available versions
of BlueCloth exist (0.0.4, 0.0.3, and 0.0.2).
Installing and Using Gem Libraries
• % gem install r BlueCloth
Attempting remote installation of 'BlueCloth'
Successfully installed BlueCloth, version 0.0.4

BlueCloth is a Ruby implementation of Markdown, a text-to-HTML


conversion tool for web writers. Markdown allows you to write using an
easy-to-read, easy-to-write plain text format, then convert it to structurally
valid XHTML (or HTML).
Generating API Documentation
• RubyGems will generate RDoc documentation
for the gem it is installing.
% gem install r BlueCloth rdoc
Attempting remote installation of 'BlueCloth'
Successfully installed BlueCloth, version 0.0.4
Installing RDoc documentation for BlueCloth0.0.4...
WARNING: Generating RDoc on .gem that may not have RDoc.
bluecloth.rb: cc..............................
Generating HTML...
Viewing API Documentation
• Open RubyGems’ documentation directory and
browse the documentation directly.
• As with most things in RubyGems, the
documentation for each gem is stored in a
central, protected, RubyGems-specific place.
• This will vary by system and by where you may
explicitly choose to install your gems.
Viewing API Documentation
• Ask the gem command where your RubyGems
main directory is located. For example:
% gem environment gemdir
/usr/local/lib/ruby/gems/1.8
• RubyGems stores generated documentation in
the doc/ subdirectory of this directory, in this
case /usr/local/lib/ruby/gems/1.8/doc. You can
open the file index.html and view the
documentation.
• If you find yourself using this path often, you
can create a shortcut
Viewing API Documentation
% gemdoc=`gem environment gemdir`/doc
% ls $gemdoc
BlueCloth0.0.4
% open $gemdoc/BlueCloth0.0.4/
rdoc/index.html
• To save time, you could declare $gemdoc in your login
shell’s profile or rc file.
Viewing API Documentation
• The second (and easier) way to view gems’ RDoc documentation is to
use RubyGems’
• included gem_server utility. To start gem_server, simply type
% gem_server
[20040718
11:28:51] INFO WEBrick 1.3.1
[20040718
11:28:51] INFO ruby 1.8.2 (20040629)
[i386mswin32]
[20040718
11:28:51] INFO WEBrick::HTTPServer#start: port=8808
• gem_server starts a Web server running on whatever computer you
run it on.
• By default, it will start on port 8808 and will serve gems and their
documentation from the default RubyGems installation directory.
• Both the port and the gem directory are overridable via command-
line options, using the p and d options, respectively
Creating Your Own Gems
• RubyGems are an ideal way for end-users to
discover, install, and uninstall your code.
• They also provide a powerful way to manage
internal, company projects, or even personal
projects, since they make upgrades and
rollbacks so simple.
Package Layout
• The first task in creating a gem is organizing
your code into a directory structure that makes
sense.
• The same rules that you would use in creating a
typical tar or zip archive apply in package
organization.
Conventions
• Put all of your Ruby source files under a
subdirectory called lib/.
• If it’s appropriate for your project, include a file
under lib/yourproject.rb that performs the
necessary require commands to load the bulk
of the project’s functionality.
• Before RubyGems’ auto require feature, this
made things easier for others to use a library.
Even with RubyGems, it makes it easier for
others to explore your code if you give them an
obvious starting point
Conventions
• Always include a README file including a project
summary, author contact information, and pointers
for getting started. Use RDoc format for this file so
you can add it to the documentation that will be
generated during gem installation. Remember to
include a copyright and license in the README file,
as many commercial users won’t use a package
unless the license terms are clear.
• Tests should go in a directory called test/. Many
developers use a library’s unit tests as a usage
guide. It’s nice to put them somewhere
predictable, making them easy for others to find.
Conventions
• Any executable scripts should go in a
subdirectory called bin/.
• Source code for Ruby extensions should go in
ext/.
• If you’ve got a great deal of documentation to
include with your gem, it’s good to keep it in its
own subdirectory called docs/.
• If your README file is in the top level of your
package, be sure to refer readers to this
location.
CS613PE SCRIPTING LANGUAGES

UNIT I
Ruby and Web:
Writing CGI Scripts

Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is Ruby in Web?
• Ruby is a server-side scripting language.
• Ruby can be used to write Common Gateway
Interface (CGI) scripts.
• Ruby can be embedded into Hypertext Markup
Language (HTML).
• Ruby has a clean and easy syntax that allows a
new developer to learn very quickly and easily.
What is CGI?

• The Common Gateway Interface (CGI) is a


standard way for a Web server to pass a Web
user's request to an application program and to
receive data back to forward to the user.
• When the user requests a Web page (for
example, by clicking on a highlighted word or
entering a Web site address), the server sends
back the requested page.
• When a user fills out a form on a Web page and
sends it in, it usually needs to be processed by
an application program.
What is CGI?

• The Web server typically passes the form


information to a small application program that
processes the data and may send back a
confirmation message.
• This method or convention for passing data
back and forth between the server and the
application is called the Common Gateway
Interface (CGI).
• It is part of the Web's Hypertext Transfer
Protocol (HTTP).
What is CGI Scripts?

• CGI Script is a simple protocol that can be used


to communicate between Web forms and your
program.
• CGI applications can be written in any
computer programming language that is
supported by the host computer.
HTTP Methods and Environment
Variable
• CGI programs commonly use the HTTP methods
– GET
– POST
• the environment variables
– QUERY_STRING
– PATH_INFO
• to facilitate communication between a client
and a Web server.
• POST is more complicated to work with, but it
supports more complex data.
Writing CGI Scripts
• The file extension for CGI is .cgi, and ruby
extension is (.rb).
[Example]
#!/usr/bin/ruby
print "Content-type: text/html\r\n\r\n"
print "<html><body>Hello World! It's
#{Time.now}</body></html>\r\n"

Output:
Content-type: text/html
<html><body>Hello World! It's 2022-03-27 15:05:42
+0000</body></html>
Writing CGI Scripts
• If Web server doesn’t automatically add headers,
add the response header.
[Example]
#!/usr/bin/ruby
print "HTTP/1.0 200 OK\r\n"
print "Content-type: text/html\r\n\r\n"
print "<html><body>Hello World! It's
#{Time.now}</body></html>\r\n"

Output:
HTTP/1.0 200 OK
Content-type: text/html
<html><body>Hello World! It's 2022-03-27 15:08:39
+0000</body></html>
Using cgi.rb

• Class CGI provides support for writing CGI


scripts.
• With it, forms, cookies, and the environment;
maintain stateful sessions; and so on can be
manipulated.
• Ruby can call CGI library to write more complex
CGI scripts.
Quoting

• When dealing with URLs and HTML code, you


must be careful to quote certain characters.
• For instance, a slash character ( / ) has special
meaning in a URL, so it must
be “escaped” if it’s not part of the pathname.
• That is, any / in the query portion of the
URL will be translated to the string %2F and
must be translated back to a / to use it.
• Space and ampersand are also special
characters.
Quoting

• To handle this, CGI provides the routines


– CGI.escape
– CGI.unescape.

Example:
require 'cgi'
puts CGI.escape("Nicholas Payton/Trumpet &
Flugel Horn")
Output
Nicholas+Payton%2FTrumpet+%26+Flugel+Horn
Quoting

• To escape HTML special characters.

require 'cgi'
puts CGI.escapeHTML("a < 100 && b > 200")

Output:
a < 100 && b > 200
Quoting
• To escape only certain HTML elements within a
string.

require 'cgi'
puts CGI.escapeElement('<hr><a href="/mp3">Click
Here</a><br>','A')

Output:
<hr>&lt;a href=&quot;/mp3&quot;&gt;Click
Here&lt;/a&gt;<br>

Here only the A element is escaped; other elements are left


alone
Quoting

• Each of these methods has an “un-” version to


restore the original string.

require 'cgi‘
puts CGI.unescapeHTML("a < 100 && b > 200")

Output:
a < 100 && b > 200
Query Parameters

• HTTP requests from the browser to your


application may contain parameters, either
passed as part of the URL or passed as data
embedded in the body of the request.
• Processing of these parameters is complicated
by the fact that a value with a given name
may be returned multiple times in the same
request.
Example
<html>
<head><title>Test Form</title></head>
<body>
I like Ruby because:
<form target="cgi-bin/survey.rb">
<input type="checkbox" name="reason" value="flexible" />
It's flexible<br />
<input type="checkbox" name="reason" value="transparent" />
It's transparent<br />
<input type="checkbox" name="reason" value="perlish" />
It's like Perl<br />
<input type="checkbox" name="reason" value="fun" />
It's fun
<p>
Your name: <input type="text" name="name">
</p>
<input type="submit"/>
</form>
</body>
</html>
Example
Query Parameters

• Class CGI gives you access to form data in a


couple of ways.
• First, CGI object is treated as a hash, indexing it
with field names and getting back field values.

require 'cgi'
cgi = CGI.new
cgi['name'] → "Dave Thomas"
cgi['reason'] → "flexible"
Query Parameters

• Class CGI gives you access to form data in a


couple of ways.
• First, CGI object is treated as a hash, indexing it
with field names and getting back field values.

require 'cgi'
cgi = CGI.new
cgi['name'] → "Dave Thomas"
cgi['reason'] → "flexible"
Query Parameters

require 'cgi'
cgi = CGI.new
cgi.params → {"name"=>["Dave Thomas"],
"reason"=>["flexible", "transparent",
"fun"]}
cgi.params['name'] →["Dave Thomas"]
cgi.params['reason'] → ["flexible",
"transparent", "fun"]
cgi.params['name'] = [ cgi['name'].upcase ]
cgi.params → {"name"=>["DAVE THOMAS"],
"reason"=>["flexible", "transparent","fun"]}
Query Parameters

• To determine, if a particular parameter is


present in a request using CGI#has_key?

require 'cgi'
cgi = CGI.new
cgi.has_key?('name') → true
cgi.has_key?('age') → false
Generating HTML

• CGI contains a huge number of methods that


can be used to create HTML—one method
per element.
• To enable these methods, a CGI object is to be
created by calling CGI.new, passing in the
required level of HTML.
Generating HTML

• To make element nesting easier, these methods


take their content as code blocks.
• The code blocks should return a String, which
will be used as the content for the element.
Example
require 'cgi'
cgi = CGI.new("html3")
cgi.out {# add HTML generation methodscgi.html {
cgi.head { "\n"+cgi.title{"This Is a Test"} } +
cgi.body { "\n"+
cgi.form {"\n"+
cgi.hr +
cgi.h1 { "A Form: " } + "\n"+
cgi.textarea("get_text") +"\n"+
cgi.br +
cgi.submit
}
}
}
}
Example - Output
Content-Type: text/html
Content-Length: 302
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2
Final//EN"><HTML><HEAD>
<TITLE>This Is a Test</TITLE></HEAD><BODY>
<FORM METHOD="post" ENCTYPE="application/x-
www-form-urlencoded">
<HR><H1>A Form: </H1>
<TEXTAREA NAME="get_text" ROWS="10"
COLS="70"></TEXTAREA>
<BR><INPUT
TYPE="submit"></FORM></BODY></HTML>
Example

• This code will produce an HTML form titled


“This Is a Test” followed by a horizontal rule, a
level-one header, a text input area, and finally a
submit button.
• When the submit comes back, you’ll have a CGI
parameter named get_text containing the text
the user entered.
Templating Systems

• Templating systems separates the presentation


and logic of your application.
• While writing a Web application using Ruby at
some point a templating system also written.
• The RubyGarden wiki lists quite a few, and
evenvthis list isn’t complete.
Templating Systems

• Some of the templating systems are


– RDoc templates
– Amrita
– erb/eruby
RDoc Templates

• The RDoc documentation system includes a


very simple templating system that it uses to
generate all its XML and HTML output.
• The templating system does not use
conventional HTML or XML markup, so files
marked up with RDoc templates may not be
easy to edit using conventional HTML editing
tools.
Example
require 'rdoc/template'
HTML = %{Hello, %name%.
<p>
The reasons you gave were:
<ul>
START:reasons
<li>%reason_name% (%rank%)
END:reasons
</ul>
}
data = {
'name' => 'Dave Thomas',
'reasons' => [
{ 'reason_name' => 'flexible', 'rank' => '87' },{ 'reason_name' => 'transparent',
'rank' => '76' },{ 'reason_name' => 'fun', 'rank' => '94' },]
}
t = TemplatePage.new(HTML)
t.write_html_on(STDOUT, data)
Example - Output
Hello, Dave Thomas.
<p>
The reasons you gave were:
<ul>
<li>flexible (87)
<li>transparent (76)
<li>fun (94)
</ ul>
Example

• The constructor is passed a string containing


the template to be used.
• The method write_html_on is then passed a
hash containing names and values.
• If the template contains the sequence %xxxx%,
the hash is consulted, and the value
corresponding to the name xxx is substituted in.
• If the template contains START:yyy, the hash
value corresponding to yyy is assumed to be an
array of hashes.
Example

• The template lines between START:yyy and


END:yyy are repeated for each element in that
array.
• The templates also support conditions: lines
between IF:zzz and ENDIF:zzz are included in
the output only if the hash has a key zzz.
Amrita
• Amrita2 is a library that generates HTML documents
from a template that is itself valid HTML.
• This makes Amrita easy to use with existing HTML
editors.
• It also means that Amrita templates display correctly as
freestanding HTML pages.
• Amrita uses the id tags in HTML elements to determine
the values to be substituted.
• If the value corresponding to a given name is nil or false,
the HTML element won’t be included in the resulting
output.
• If the value is an array, it iterates the corresponding
HTML element.
Example
require 'amrita/template'
include Amrita
HTML = %{<p id="greeting" />
<p>The reasons you gave were:</p>
<ul>
<li id="reasons"><span id="reason_name"></span>,
<span id="rank"></span>
</ul>
} data = {
:greeting => 'Hello, Dave Thomas',
:reasons => [
{ :reason_name => 'flexible', :rank => '87' },
{ :reason_name => 'transparent', :rank => '76' },
{ :reason_name => 'fun', :rank => '94' },
]}
t = TemplateText.new(HTML)
t.prettyprint = true
t.expand(STDOUT, data)
Example - Output
<p>Hello, Dave Thomas</p>
<p>The reasons you gave were:</p>
<ul>
<li>flexible, 87 </li>
<li>transparent, 76 </li>
<li>fun, 94 </li>
</ul>
erb and eruby

• A number of packages allow to embed Ruby


statements in some other sort of a
document, especially in an HTML page.
• Generically, this is known as “eRuby.”
• Several different implementations of eRuby
exist, including eruby and erb.
• eruby, written by Shugo Maeda, is available for
download from the Ruby Application Archive.
• erb, its little cousin, is written in pure Ruby and
is included with the standard distribution.
Using erb

• erb is normally used as a filter.


• Text within the input file is passed through
untouched, with the exceptions.

Syntax:
erb can be invoked as
erb [ options ] [ document ]

If the document is omitted, eruby will read from


standard input.
Using erb - exceptions

Expression Description
<% ruby code %> Execute the Ruby code
between the delimiters.
<%= ruby expression Evaluate the Ruby expression,
%> and replace the sequence with
the expression’s value.
<%= ruby expression The Ruby code between the
%> delimiters is ignored
% line of ruby code A line that starts with a percent
is assumed to contain just Ruby
code
Using erb – Command-line options

Option Description
-d Sets $DEBUG to true
-Kkcode Specifies an alternate encoding
system
-n Display resulting Ruby script
-r library Loads the named library
-P Doesn’t do erb processing on lines
starting %
-S level Sets the safe level
-T mode Sets the trim mode
-v Enables verbose mode
-x Displays resulting Ruby script
Erb – Example

% a = 99
<%= a %> Pack of Apples

• The line starting with the percent sign simply


executes the given Ruby statement.
• The next line contains the sequence <%= a %>,
which substitutes in the value of a.
erb f1.erb
Output:
99 Pack of Apples
Erb – Example

• erb works by rewriting its input as a Ruby


script and then executing that script.
• The Ruby that erb generates using the n or x
option.
erb x f1.erb
Output:
_erbout = ''; a = 99
_erbout.concat(( a ).to_s); _erbout.concat " Pack
of Apples...\n"
_erbout
Erb – Example

• erb builds a string, _erbout, containing both


the static strings from the template and the
results of executing expressions.
Ruby embedded in HTML
• erb processing a file with loops
<!DOCTYPE HTML PUBLIC "//
W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>eruby example</title>
</head>
<body>
<h1>Enumeration</h1>
<ul>
%5.times do |i|
<li>number <%=i%></li>
%end
Ruby embedded in HTML

</ul>
<h1>"Environment variables starting with "T"</h1>
<table>
%ENV.keys.grep(/^T/).each do |key|
<tr><td><%=key%></td><td><%=ENV[key]%></td<
</tr>
%end
</table>
</body>
</html>
Ruby embedded in HTML
Output:
<!DOCTYPE HTML PUBLIC "//
W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>eruby example</title>
</head>
<body>
<h1>Enumeration</h1>
<ul>
<li>number 0</li>
<li>number 1</li>
<li>number 2</li>
<li>number 3</li>
<li>number 4</li>
</ul>
Ruby embedded in HTML
<h1>"Environment variables starting with "T"</h1>
<table>
<tr><td>TERM_PROGRAM</td><td>Apple_Terminal<
/td></tr>
<tr><td>TERM</td><td>xtermcolor</
td></tr>
<tr><td>TERM_PROGRAM_VERSION</td><td>133</t
d></tr>
<tr><td>TYPE</td><td>SCREEN</td></tr>
</table>
</body>
</html>
Installing eruby in Apache

• To use erb-like page generation for a website


that gets a reasonable amount of traffic, switch
across to eruby, which has better performance.
• Then configure the ApacheWeb server to
automatically parse Rubyembedded
documents using eRuby.
• Create Ruby-embedded files with an .rhtml
suffix and configure the Web server to run the
eruby executable on these documents to
produce the desired HTML output.
Steps to use eruby with Apache Web
server
• Copy the eruby binary to the cgibin directory.
• Add the following two lines to httpd.conf.
AddType application/xhttpderuby .rhtml
Action application/xhttpderuby/cgibin/eruby
• If preferred, add or replace the DirectoryIndex
directive such that it includes index.rhtml.
• This allows Ruby to create directory listings for
directories that do not contain an index.html.
• For instance, the following directive would cause the
embedded Ruby script index.rhtml to be searched for
and served if neither index.html nor index.shtml
existed in a directory.
Steps to use eruby with Apache Web
server
DirectoryIndex index.html index.shtml index.rhtml
• A sitewide Ruby script also can be used as well.
DirectoryIndex index.html index.shtml /cgibin/index.rb
Cookies
• Cookies are a way of letting Web applications
store their state on the user’s machine.
• Cookies are a convenient way of remembering
session information.
• The Ruby CGI class handles the loading and saving
of cookies.
• The cookies associated with the current request
can be accessed using the CGI#cookies method,
and cookies can be set back into the browser by
setting the cookies parameter of CGI#out to
reference either a single cookie or an array of
cookies.
Cookies - Examples
#!/usr/bin/ruby
COOKIE_NAME = 'chocolate chip'
require 'cgi'
cgi = CGI.new
values = cgi.cookies[COOKIE_NAME]
if values.empty?
msg = "It looks as if you haven't visited recently"
else
msg = "You last visited #{values[0]}"
end
cookie = CGI::Cookie.new(COOKIE_NAME, Time.now.to_s)
cookie.expires = Time.now + 30*24*3600 # 30 days
cgi.out("cookie" => cookie ) { msg }
Sessions
• Session information persists between requests
from a particular Web browser.
• Sessions are handled by class CGI::Session, which
uses cookies but provides a higher-level
abstraction.
• Sessions follow a hash like behavior, allowing to
associate values with keys.
• Sessions store the majority of their data on the
server, using the browser-resident cookie simply as
a way of uniquely identifying the server-side data.
• Sessions also give a choice of storage techniques
for this data: it can be held in regular files, in a
PStore, in memory, or even in your own
customized store.
Sessions

• Sessions should be closed after use, as this


ensures that their data is written out to the
store.
• When sessions are permanently finished,
delete it.
Sessions - Example
require 'cgi'
require 'cgi/session'
cgi = CGI.new("html3")
sess = CGI::Session.new(cgi,
"session_key" => "rubyweb",
"prefix" => "websession."
)
if sess['lastaccess']
msg = "You were last here #{sess['lastaccess']}."
else
msg = "Looks like you haven't been here for a while"
end
Sessions - Example
count = (sess["accesscount"] || 0).to_i
count += 1
msg << "<p>Number of visits: #{count}"
sess["accesscount"] = count
sess["lastaccess"] = Time.now.to_s
sess.close
cgi.out {
cgi.html {
cgi.body {
msg
}
}
}
Sessions-Example

• The filenames all will start with web session


and will end with a hashed version of the
session number.
Choice of Web Servers
• Ruby scripts can be run under the control of the
Apache Web server.
• Ruby 1.8 and later version of Ruby bundled with
WEBrick, a flexible, pure-Ruby HTTP server toolkit.
• It’s an extensible plug in–based framework that
lets to write servers to handle HTTP requests and
responses.
• Here’s a basic HTTP server that serves documents
and directory indexes.
Choice of Web Servers - Example

#!/usr/bin/ruby
require 'webrick'
include WEBrick
s = HTTPServer.new(
:Port => 2000,
:DocumentRoot => File.join(Dir.pwd, "/html")
)
trap("INT") { s.shutdown }
s.start
Choice of Web Servers - Example

• The HTTPServer constructor creates a new Web


server on port 2000.
• The code sets the document root to be the html/
subdirectory of the current directory. It then uses
Kernel.trap to arrange to shut down neatly on
interrupts before starting the server running.
• WEBrick can be used like a Java servlet container.
Choice of Web Servers - Example
#!/usr/bin/ruby
require 'webrick'
include WEBrick
s = HTTPServer.new( :Port => 2000 )
class HelloServlet < HTTPServlet::AbstractServlet
def do_GET(req, res)
res['Content-Type'] = "text/html"
res.body = %{
<html><body>
Hello. You're calling from a #{req['User-Agent']}
<p>
I see parameters: #{req.query.keys.join(', ')}
</body></html>
}
end
end
s.mount("/hello", HelloServlet)
trap("INT"){ s.shutdown }
s.start
Choice of Web Servers - Example

• The following code mounts a simple servlet at


the location /hello.
• As requests arrive, the do_GET method is
invoked.
• It uses the response object to display the user
agent information and parameters from the
request.
SOAP and Web Services

• Ruby allows implementation of SOAP that lets to


write both servers and clients using Web services.
• These applications can operate both locally and
remotely across a network.
• SOAP is a convenient way of interconnecting Ruby
applications with those written in languages such
as Java, Visual Basic, or C++.
SOAP Working Process
• SOAP is uses XML to send data between two nodes
in a network.
• It is used to implement remote procedure calls,
RPCs, between distributed processes.
• A SOAP server publishes one or more interfaces.
• These interfaces are defined in terms of data types
and methods that use those types.
• SOAP clients then create local proxies that SOAP
connects to interfaces on the server.
• A call to a method on the proxy is then passed to
the corresponding interface on the server.
• Return values generated by the method on the
server are passed back to the client via the proxy.
SOAP Example

Regular Ruby Code:


class InterestCalculator
attr_reader :call_count
def initialize
@call_count = 0
end
def compound(principal, rate, freq, years)
@call_count += 1
principal*(1.0 + rate/freq)**(freq*years)
end
end
SOAP Example
SOAP Server side Code:
require 'soap/rpc/standaloneServer'
require 'interestcalc'
NS = 'http://pragprog.com/InterestCalc'
class Server2 < SOAP::RPC::StandaloneServer
def on_init
calc = InterestCalculator.new
add_method(calc, 'compound', 'principal', 'rate', 'freq',
'years')
add_method(calc, 'call_count')
end
end
svr = Server2.new('Calc', NS, '0.0.0.0', 12321)
trap('INT') { svr.shutdown }
svr.start
SOAP Example
SOAP Client side Code:
require 'soap/rpc/driver'
proxy =
SOAP::RPC::Driver.new("http://localhost:12321",
"http://pragprog.com/InterestCalc")
proxy.add_method('compound', 'principal', 'rate',
'freq', 'years')
proxy.add_method('call_count')
puts "Call count: #{proxy.call_count}"
puts "5 years, compound annually:
#{proxy.compound(100, 0.06, 1, 5)}"
puts "5 years, compound monthly:
#{proxy.compound(100, 0.06, 12, 5)}"
puts "Call count: #{proxy.call_count}"
SOAP Example
• The client creates a local proxy for the
InterestCalculator service on the server, adds the
methods it wants to use, and then calls them.
• To test this, we can run the server in one console
window.
% ruby server.rb
I, [2004-07-26T10:55:51.629451 #12327]
-- Calc: Start of Calc.
I, [2004-07-26T10:55:51.633755 #12327]
-- Calc: WEBrick 1.3.1
I, [2004-07-26T10:55:51.635146 #12327] INFOINFOINFO-- Calc: ruby
1.8.2 (2004-07-26) [powerpc-darwin]I, [2004-07-26T10:55:51.639347
#12327] INFO-- Calc: WEBrick::HTTPServer#start: pid=12327
port=12321
SOAP Example
% ruby client.rb
Call count: 0
5 years, compound annually: 133.82255776
5 years, compound monthly: 134.885015254931
Call count: 2
Looking good! Flush with success, we call all our
friends over and run it again.
% ruby client.rb
Call count: 2
5 years, compound annually: 133.82255776
5 years, compound monthly: 134.885015254931
Call count: 4
CS613PE SCRIPTING LANGUAGES

UNIT I
RUBY Tk

Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is Ruby Tk?

• The standard Graphical User Interface (GUI) for


Ruby is Tk.
• Tk started out as the GUI for the Tcl scripting
language developed by John Ousterhout.
• Tk runs on Windows, Mac, and Linux and provides
a native look-and-feel on each operating system.
Tk Component

• The basic component of a Tk-based application


is called a widget.
• A component is also sometimes called a
window, since, in Tk, "window" and "widget"
are often used interchangeably.
• Tk applications follow a widget hierarchy where
any number of widgets may be placed within
another widget..
• The main widget in a Tk program is referred to
as the root widget and can be created by
making a new instance of the TkRoot class.
Ruby Tk Working Process

• Tk works along a composition model.


• It is started by
– creating a container (such as a TkFrame or TkRoot)
– then creating the widgets (another name for GUI
components) that populate it, such as buttons or
labels.
• To start the GUI, invoke Tk.mainloop.
• The Tk engine then takes control of the
program, displaying widgets and calling the
code in response to GUI events.
Simple Tk Application

require 'tk'
root = TkRoot.new { title "Ex1" }
TkLabel.new(root) do
text 'Hello, World!'
pack('padx' => 15, 'pady' => 15, 'side' => 'left')
end
Tk.mainloop
Simple Tk Application
• After loading the tk extension module, create a
root-level frame using TkRoot.new.
• Then make a TkLabel widget as a child of the root
frame, setting several options for the label.
• Finally, pack the root frame and enter the main
GUI event loop.
Widgets
• A widget is an element of a Graphical User
Interface (GUI) that displays information or
provides a specific way for a user to interact with
the operating system or an application.
• Widgets include icons, pull-down menus, buttons,
selection boxes, progress indicators, on-off
checkmarks, scroll bars, windows, window edges
(that let you resize the window), toggle buttons,
form, and many other devices for displaying
information and for inviting, accepting, and
responding to user actions.
• In Ruby Tk, create an instance of a widget using
new.
Setting Widget Options
• The name of the option is used as a method name within the block
and arguments to the option appear
as arguments to the method call.
Widgets take a parent as the first argument, followed by an optional
hash of options or the code block of options. Thus, the following two
forms are equivalent.

TkLabel.new(parent_widget) do
text 'Hello, World!'
pack('padx' => 5,
'pady' => 5,
'side' => 'left')
end

# or
TkLabel.new(parent_widget, 'text' => 'Hello, World!').pack(...)
Setting Widget Options
• A widget is an element of a Graphical User
Interface (GUI) that displays information or
provides a specific way for a user to interact with
the operating system or an application.
• Widgets include icons, pull-down menus, buttons,
selection boxes, progress indicators, on-off
checkmarks, scroll bars, windows, window edges
(that let you resize the window), toggle buttons,
form, and many other devices for displaying
information and for inviting, accepting, and
responding to user actions.
• In Ruby Tk, create an instance of a widget using
new.
Setting Widget Options

TkLabel.new(parent_widget) do
text 'Hello, World!'
pack('padx' => 5,'pady' => 5,'side' => 'left')
end

# or

TkLabel.new(parent_widget, 'text' =>


'Hello, World!').pack(...)
Getting Widget Data

• The command option (shown in the TkButton


call in the example that follows) takes a Proc
object, which will be called when the callback
fires.
Getting Widget Data - Example

require 'tk'
TkButton.new do
text "EXIT"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
Tk.mainloop
Getting Widget Data

• Ruby variables can be bind to a Tk widget’s


value using a TkVariable proxy.
• Whenever the widget’s value changes, the
Ruby variable will automatically be updated
and whenever the variable is changed, the
widget will reflect the new value.
TkCheckButton

• Tk variable reference is created using


TkVariable.new.
• Accessing mycheck.value will return the string
“0” or “1” depending on whether the checkbox
is checked.
TkCheckButton - Example

require 'tk'
packing = { 'padx'=>5, 'pady'=>5, 'side' => 'left' }
checked = TkVariable.new
def checked.status
value == "1" ? "Yes" : "No"
end status = TkLabel.new do
text checked.status
pack(packing)
end
TkCheckButton - Example

TkCheckButton.new do
variable checked
pack(packing)
end
TkButton.new do
text "Show status"
command { status.text(checked.status) }
pack(packing)
end
Tk.mainloop
Setting/Getting Options Dynamically

• A widget can be reconfigured while it’s running.


• Every widget supports the configure method,
which takes a Hash or a code block in the same
manner as new.
Example
require 'tk'
root = TkRoot.new { title "Ex3" }
top = TkFrame.new(root) { relief 'raised'; border 5 }
lbl = TkLabel.new(top) do
justify 'center'
text 'Hello, World!'
pack('padx'=>5, 'pady'=>5, 'side' => 'top')
end
TkButton.new(top) do
text "Ok"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
TkButton.new(top) do
text "Cancel"
command { lbl.configure('text'=>"Goodbye, Cruel World!") }
pack('side'=>'right', 'padx'=>10, 'pady'=>10)
end
top.pack('fill'=>'both', 'side' =>'top')
Tk.mainloop
Example

• Now when the Cancel button is clicked, the


text in the label will change immediately from
“Hello, World!” to “Goodbye, Cruel World!”.
Binding Events

• Use widget’s bind method to create a binding


from an event on a particular widget to a block
of code.
Example
require 'tk'
image1 = TkPhotoImage.new { file "img1.gif" }
image2 = TkPhotoImage.new { file "img2.gif" }
b = TkButton.new(@root) do
image image1
command { exit }
pack
end
b.bind("Enter") { b.configure('image'=>image2) }
b.bind("Leave") {b.configure('image'=>image1) }
Tk.mainloop
Binding Events

• First, we create two GIF image objects from files


on disk, using TkPhotoImage.
• Next, create a button, which displays the image
image1.
• Then bind the Enter event so that it dynamically
changes the image displayed by the button to
image2 when the mouse is over the button, and
the Leave event to revert back to image1 when
the mouse leaves the button
Queries?
THANK YOU!

You might also like