[go: up one dir, main page]

0% found this document useful (0 votes)
20 views54 pages

SL Unit-I

Scripting language unit 1
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)
20 views54 pages

SL Unit-I

Scripting language unit 1
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/ 54

UNIT – I

1.1 Introduction
1.1.1 Ruby
Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz
in the Ruby community) in the mid 1990’s in Japan. Everything in Ruby is an object except the
blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s
development was to make it act as a sensible buffer between human programmers and the underlying
computing machinery. Ruby has similar syntax to that of many programming languages like C and
Java, so it is easy for Java and C programmers to learn. It supports mostly all the platforms like
Windows, Mac, Linux.

Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted
scripting language which means most of its implementations execute instructions directly and freely,
without previously compiling a program into machine-language instructions. Ruby programmers
also have access to the powerful RubyGems (RubyGems provides a standard format for Ruby
programs and libraries).
Beginning with Ruby programming:
1. Finding a Compiler:
Before starting programming in Ruby, a compiler is needed to compile and run our programs. There
are many online compilers that can be used to start Ruby without installing a compiler:
https://www.jdoodle.com/execute-ruby-online
https://repl.it/
There are many compilers available freely for compilation of Ruby programs.
2. Programming in Ruby:
To program in Ruby is easy to learn because of its similar syntax to already widely used languages.
Writing program in Ruby:
Programs can be written in Ruby in any of the widely used text editors like Notepad++, gedit etc.
After writing the programs save the file with the extension .rb
Let’s see some basic points of programming:
Comments: To add single line comments in Ruby Program, # (hash) is used.
Syntax:
# Comment
To add multi-line comments in Ruby, a block of =begin and =end (reserved key words of Ruby) are
used.
Syntax:
=begin
Statement 1
Statement 2
...
Statement n
=end

 Sample Ruby Code

Here is a sample Ruby code to print "Hello Ruby"

# The Hello Class


class Hello

def initialize( name )


@name = name.capitalize
end

def salute
puts "Hello #{@name}!"
end

end

# Create a new object


h = Hello.new("Ruby")

# Output "Hello Ruby!"


h.salute

Output

Hello Ruby!

 Advantages of Ruby:
 The code written in Ruby is small, elegant and powerful as it has fewer number of lines of
code.
 Ruby allows simple and fast creation of Web application which results in less hard work.
 As Ruby is free of charge that is Ruby is free to copy, use, modify, it allow programmers to
make necessary changes as and when required.
 Ruby is a dynamic programming language due to which there is no tough rules on how to
built in features and it is very close to spoken languages.
 Disadvantages of Ruby:

 Ruby is fairly new and has its own unique coding language which makes it difficult for the
programmers to code in it right away but after some practice its easy to use. Many programmers
prefer to stick to what they already know and can develop.
 The code written in Ruby is harder to debug, since most of the time it generates at runtime, so it
becomes difficult to read while debugging.
 Ruby does not have a plenty of informational resources as compared to other programming
languages.
 Ruby is an interpreted scripting language, the scripting languages are usually slower than
compiled languages therefore, Ruby is slower than many other languages.
 Applications:
 Ruby is used to create web applications of different sorts. It is one of the hot technology at present
to create web applications.
 Ruby offers a great feature called Ruby on Rails (RoR). It is a web framework that is used by
programmers to speed up the development process and save time.

1.1.2 Rails
Ruby on Rails or also known as rails is a server-side web application development framework that
is written in the Ruby programming language, and it is developed by David Heinemeier Hansson
under the MIT License. It supports MVC(model-view-controller) architecture that provides a default
structure for database, web pages, and web services, it also uses web standards like JSON or XML
for transfer data and HTML, CSS, and JavaScript for the user interface. It emphasizes the use of
other well-known software engineering pattern and paradigms like:
 Don’t Repeat Yourself (DRY): It is a principle of software development to reducing the
repetition of information or codes.
 Convention Over Configuration (CoC): It provides many opinions for the best way to do many
things in a web application.
Ruby on Rails was first released in July 2004 but until February 2005 did not share the commit
rights. In August 2006, it would ship Ruby on Rails with Mac OS X v10.5 “Leopard”. Ruby on Rail’s
latest version(Rail 5.0.1) released on December 21, 2016. Action cable, Turbolinks 5, and API mode
Introduced in this version.
 Why Ruby on Rails?
 It allows you to launch a faster web application.
 Saves your money by using the Ruby on Rails framework.
 Helps us with maintaining and avoiding problems with stuff migration.
 Ruby on Rail Framework makes our app faster and safer.
 We can easily update our app with the latest functionality.
 It uses Metaprogramming techniques to write programs.

 Where to use Ruby on Rails?


You can use Ruby on Rails application in various area of web development like in a long term project
which needs large transformation, or in the project that has heavy traffic, or to develop a short
prototype or MVPs, or in a project that requires wide range of complex functions, etc.

 Features of Ruby on Rails

As we know that most of the languages like Java, HTML, CSS, etc. do not cover the front end and
back end. They either only for the back end or for the front end but Ruby on Rails is used for both
front end back end, it is like a complete package to develop a web application. Some important
features of Ruby on Rails are:

1. Model-view-controller Architecture: Ruby on Rails used MVC architecture, and it contains


three components, i.e., model, view, and controller. Here, the model is used to maintain the
relationship between object and database, the view is templates that are used to build the data users
for web applications, and the controller is used to merge model and view together. MVC is generally
used for developing user interfaces that divide the data into three interconnected components so that
it can separate the internal representation of the information from the way it presents to and get from
the user.
2. Active Records: The active record framework is introduced in Ruby on Rails. It is a powerful
library that allows the developer to design the database interactive queries.
3. Built-in Testing: Ruby on Rails provides its own set of tests that will run on your code. It will
save time and effort.
4. Programming Language: This syntax of Ruby on Rails is simple because the syntax of the Ruby
programming language is close to English, so it is always easier to structure your thinking and
writing it into code.
5. MetaProgramming: Ruby on rails uses the metaprogramming technique to write programs.
6. Convention over configuration: In Ruby on Rails, a programmer can only specify the
unconventional aspects of the application.
7. Scaffolding: Ruby on rails provides a scaffolding feature in which the developer is allowed to
define how the application database works. After defining the work of the application database the
framework automatically generates the required code according to the given definition. This
technique creates interfaces automatically.

 Advantages of Ruby on Rails

 Tooling: Rails provides tooling that helps us to deliver more features in less time.
 Libraries: There’s a 3rd party module(gem) for just about anything we can think of.
 Code Quality: Ruby code quality significantly higher than PHP or NodeJS equivalents.
 Test Automation: The Ruby community is big into and test automation and testing.
 Large Community: Ruby is large in the community.
 Productivity: Ruby is incredibly fast from another language. Its productivity is high.

 Disadvantages of Ruby on Rails

 Runtime Speed: The run time speed of Ruby on Rails is slow as compare to Node.Js and Golang.
 Lack of Flexibility: As we know that Ruby on Rails is ideal for standard web applications due
to its hard dependency between components and models. But when it comes to adding unique
functionality and customization in apps it is challenging.
 Boot Speed: The boot speed is also a drawback of ROR. Due to the dependence upon the number
of gem dependencies and files, it takes some time to start which can obstruct the developer
performance.
 Documentation: To find good documentation is hard for the less popular gems and for libraries
that make heavy use of mixins.
 Multithreading: Ruby on Rails supports multithreading, but some IO libraries do not support
multithreading because they keep hold of the global interpreter lock. So it means if you are not
careful enough, your request will get queued up behind the active requests, and you will face
performance issues.
 Active Record: Due to the access use of Active records in the ROR and hard dependency, the
domain becomes tightly coupled to your persistence mechanism.
 Example:
To create a rails application you need to follow the following steps:

Step 1: Open a terminal and write the following command. This command creates an application
with the name ‘myFirstProject’.
rails new myFirstProject
Step 2: Now we move into our application directory.
cd myFirstProject

Here, myFirstProject contains these files.

Step 3: Now we create a rails server using the following command.


bin/rails s

or

bin/rails server
By default, the rails server uses port 3000. If you want to change the port number we can use the
following command:

rails server -p portNumber

Now open the browser and open http://localhost:3000/. If your server works properly then you will
get this page.
Step 4: Open another terminal and move to myFirstProject directory. Now we create a controller
named ‘sample’ for our home page.
rails generate controller sample
Step 5: Now we add an index page. So open sublime text and write the following HTML code and
save the file with name index.html.erb, and in location:
/myFirstProject/app/views/sample/index.html.erb.
<h3>My first ruby on rails application</h3>

Step 6: After creating index page, we need to route the ruby on rails to this page. So for that open
routes.rb file which is present in location: /myFirstProject/config/routes.rb. Now write the following
line in the routes.rb file
root'sample#index'

Step 7: Now refresh the browser window to see the final output.

1.1.3 The Structure and Execution of Ruby Programs

The basic structure of Ruby programs. It starts with the lexical structure, covering tokens and the
characters that comprise them. Next, it covers the syntactic structure of a Ruby program, explaining
how expressions, control structures, methods, classes, and so on are written as a series of tokens.
1. Lexical Structure
The Ruby interpreter parses a program as a sequence of tokens. Tokens include comments, literals,
punctuation, identifiers, and keywords. This section introduces these types of tokens and also includes
important information about the characters that comprise the tokens and the whitespace that separates
the tokens.

 Comments
Comments in Ruby begin with a # character and continue to the end of the line. 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:

# 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

 Literals
Literals are values that appear directly in Ruby source code. They include numbers, strings of text, and
regular expressions. For example :

1 # An integer literal
2 # A floating-point literal
3 'one' # A string literal
4 "two" # Another string literal
5 /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 simply a name. Ruby uses identifiers to name variables, methods, classes, and so forth.
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, and they may not include
punctuation characters except as described here.

Identifiers that begin with a capital letter A–Z are constants, and the Ruby interpreter will issue a
warning (but not an error) if you alter the value of such an identifier. Class and module names must
begin with initial capital letters.
The following are identifiers:

x2

old_value_internal # Identifiers may begin with underscores

PI # Constant

By convention, multiword identifiers that are not constants are written with underscores
like_this, whereas multiword constants are written LikeThis or LIKE_THIS.

 Punctuation in identifiers

Punctuation characters may appear at the start and end of Ruby identifiers. They have the following
meanings:

$ - Global variables are prefixed with a dollar sign.

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

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

Here are some example identifiers that contain leading or trailing punctuation characters:

$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

The following keywords have special meaning in Ruby and are treated specially by the Ruby parser:

__LINE__ case ensure not then

__ENCODING__ class false or true

__FILE__ def for redo undef

BEGIN defined? if rescue unless

END do in retry until

alias else module return when

and elsif next self while

begin end nil super yield

break

2. Syntactic Structure
The basic unit of syntax in Ruby is the expression. The Ruby interpreter evaluates expressions,
roducing values. The simplest expressions are primary expressions, which represent values
directly. Operators are used to perform computations on values, and compound expressions are built
by combining simpler subexpressions with operators:

1 # A primary expression

x # Another primary expression

x=1 # An assignment expression

x=x+1 # An expression with two operators


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

 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. There are two kinds of blocks in
Ruby programs. One kind is formally called a “block.” These blocks are the chunks of code associated
with or passed to iterator methods:

3.times { print "Ruby! " }

In this code, the curly braces and the code inside them are the block associated with the iterator method
invocation 3.times. Formal blocks of this kind may be delimited with curly braces, or they may be
delimited with the keywords do and end:

1.upto(10) do |x|

print x

end

do and end delimiters are usually used when the block is written on more than one line.

 File Structure

There are only a few rules about how a file of Ruby code must be structured. These rules are related to
the deployment of Ruby programs and are not directly relevant to the language itself.
First, if a Ruby program contains a “shebang” comment, to tell the (Unix-like) operating system how

to execute it, that comment must appear on the first line.


Second, if a Ruby program contains a “coding” comment (as described in §2.4.1), 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. (See Chapter 10
and §9.7 for more about this global constant.)

Ruby programs are not required to fit in a single file. Many programs load additional Ruby code from
external libraries, for example. Programs use require to load code from another file. require searches
for specified modules of code against a search path, and prevents any given module from being loaded
more than once.

The following code illustrates each of these points of Ruby file structure:

#!/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 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, for example.

Programmers who are used to traditional static compiled languages like C or Java may find this slightly
confusing. There is no special main method in Ruby from which execution begins. 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 is invoked from the command line and given a script to execute. Very simple
one-line scripts are sometimes written directly on the command line. More commonly, however, the
name of the file containing the script is specified. The Ruby interpreter reads the file and executes the
script.

1.1.4 Package Management with RUBYGEMS

RubyGems is a package utility for Ruby, which installs Ruby software packages and keeps them up-
to-date.

 Usage Syntax

$ gem command [arguments...] [options...]


 Example

Check to see whether RubyGems is installed −

$ gem --version
0.9.0

 RubyGems Commands

Here is a list of all important commands for RubyGems −

Sr.No. Command & Description

1 build
Builds a gem from a gemspec.

2 cert
Adjusts RubyGems certificate settings.

3 check
Checks installed gems.

4 cleanup
Cleans up old versions of installed gems in the local repository.

5 contents
Displays the contents of the installed gems.

6 dependency
Shows the dependencies of an installed gem.

7 environment
Displays RubyGems environmental information.

8
help
Provides help on the 'gem' command.

9 install
Installs a gem into the local repository.

10 list
Displays all gems whose name starts with STRING.

11 query
Queries gem information in local or remote repositories.

12 rdoc
Generates RDoc for pre-installed gems.

13 search
Displays all gems whose name contains STRING.

14 specification
Displays gem specification (in yaml).

15 uninstall
Uninstalls a gem from the local repository.

16 unpack
Unpacks an installed gem to the current directory.

17 update
Updates the named gem (or all installed gems) in the local repository.

 RubyGems Common Command Options

Following is the list of common options −

Sr.No. Command & Description

1 --source URL
Uses URL as the remote source for gems.

2 -p, --[no-]http-proxy [URL]


Uses HTTP proxy for remote operations.

3 -h, --help
Gets help on this command.

4 --config-file FILE
Uses this config file instead of default.

5 --backtrace
Shows stack backtrace on errors.
6 --debug
Turns on Ruby debugging.

 RubyGems Install Command Options

This is a list of the options, which use most of the time when you use RubyGems while installing any
Ruby package −

Sr.No. Command & Description

1 -v, --version VERSION


Specifies version of gem to install.

2 -l, --local
Restricts operations to the LOCAL domain (default).

3 -r, --remote
Restricts operations to the REMOTE domain.

4 -b, --both
Allows LOCAL and REMOTE operations.

5 -i, --install-dir DIR


Where to install.

6 -d, --[no-]rdoc
Generates RDoc documentation for the gem on install.

7 -f, --[no-]force
Forces gem to install, bypassing dependency checks.

8 -t, --[no-]test
Runs unit tests prior to installation.

9 -w, --[no-]wrappers
Uses bin wrappers for executables.

10 -P, --trust-policy POLICY


Specifies gem trust policy.

11 --ignore-dependencies
Do not install any required dependent gems.

12 -y, --include-dependencies
Unconditionally installs the required dependent gems.
 Examples

This will install 'SOAP4R', either from local directory or remote server including all the dependencies

gem install soap4r --include-dependencies

This will install 'rake', only from remote server −

gem install rake --remote

This will install 'rake' from remote server, and run unit tests, and generate RDocs −

gem install --remote rake --test --rdoc –ri

 Standard Ruby Tools

The standard Ruby distribution contains useful tools along with the interpreter and standard libraries:

These tools help you debug and improve your Ruby programs without spending much effort. This
tutorial will give you a very good start with these tools.

 RubyGems −
RubyGems is a package utility for Ruby, which installs Ruby software packages and keeps
them up-to-date.
 Ruby Debugger −
To help deal with bugs, the standard distribution of Ruby includes a debugger. This is very
similar to gdb utility, which can be used to debug complex programs.
 Interactive Ruby (irb) −
irb (Interactive Ruby) was developed by Keiju Ishitsuka. It allows you to enter commands at
the prompt and have the interpreter respond as if you were executing a program. irb is useful
to experiment with or to explore Ruby.
 Ruby Profiler −
Ruby profiler helps you to improve the performance of a slow program by finding the
bottleneck.
 Additional Ruby Tools

There are other useful tools that don't come bundled with the Ruby standard distribution. However,
you do need to install them yourself.

 eRuby: Embeded Ruby −


eRuby stands for embedded Ruby. It's a tool that embeds fragments of Ruby code in other files,
such as HTML files similar to ASP, JSP and PHP.
 ri: Ruby Interactive Reference −
When you have a question about the behavior of a certain method, you can invoke ri to read
the brief explanation of the method.

1.2 Ruby and Web


1.2.1 Writing CGI scripts

Ruby is a general-purpose language; it can't properly be called a web language at all. Even so, web
applications and web tools in general are among the most common uses of Ruby.

Not only can you write your own SMTP server, FTP daemon, or Web server in Ruby, but you can also
use Ruby for more usual tasks such as CGI programming or as a replacement for PHP.

Please spend few minutes with CGI Programming Tutorial for more detail on CGI Programming.

The most basic Ruby CGI script looks like this −

#!/usr/bin/ruby

puts "HTTP/1.0 200 OK"


puts "Content-type: text/html\n\n"
puts "<html><body>This is a test</body></html>"

If you call this script test.cgi and uploaded it to a Unix-based Web hosting provider with the right
permissions, you could use it as a CGI script.

For example, if you have the Web site https://www.example.com/ hosted with a Linux Web hosting
provider and you upload test.cgi to the main directory and give it execute permissions, then
visiting https://www.example.com/test.cgi should return an HTML page saying This is a test.
Here when test.cgi is requested from a Web browser, the Web server looks for test.cgi on the Web site,
and then executes it using the Ruby interpreter. The Ruby script returns a basic HTTP header and then
returns a basic HTML document.

 Using cgi.rb

Ruby comes with a special library called cgi that enables more sophisticated interactions than those
with the preceding CGI script.

Let's create a basic CGI script that uses cgi −

#!/usr/bin/ruby

require 'cgi'
cgi = CGI.new

puts cgi.header
puts "<html><body>This is a test</body></html>"

Here, you created a CGI object and used it to print the header line for you.

 Form Processing

Using class CGI gives you access to HTML query parameters in two ways. Suppose we are given a
URL of /cgi-bin/test.cgi?FirstName = Zara&LastName = Ali.

You can access the parameters FirstName and LastName using CGI#[] directly as follows −

#!/usr/bin/ruby

require 'cgi'
cgi = CGI.new
cgi['FirstName'] # => ["Zara"]
cgi['LastName'] # => ["Ali"]

There is another way to access these form variables. This code will give you a hash of all the key and
values −

#!/usr/bin/ruby

require 'cgi'
cgi = CGI.new
h = cgi.params # =>
{"FirstName"=>["Zara"],"LastName"=>["Ali"]}
h['FirstName'] # => ["Zara"]
h['LastName'] # => ["Ali"]

Following is the code to retrieve all the keys −

#!/usr/bin/ruby

require 'cgi'
cgi = CGI.new
cgi.keys # => ["FirstName", "LastName"]

If a form contains multiple fields with the same name, the corresponding values will be returned to the
script as an array. The [] accessor returns just the first of these.index the result of the params method
to get them all.

In this example, assume the form has three fields called "name" and we entered three names "Zara",
"Huma" and "Nuha" −

#!/usr/bin/ruby

require 'cgi'
cgi = CGI.new
cgi['name'] # => "Zara"
cgi.params['name'] # => ["Zara", "Huma", "Nuha"]
cgi.keys # => ["name"]
cgi.params # => {"name"=>["Zara", "Huma", "Nuha"]}

Note − Ruby will take care of GET and POST methods automatically. There is no separate treatment
for these two different methods.

An associated, but basic, form that could send the correct data would have the HTML code like so −

<html>
<body>
<form method = "POST" action =
"http://www.example.com/test.cgi">
First Name :<input type = "text" name = "FirstName"
value = "" />
<br />
Last Name :<input type = "text" name = "LastName"
value = "" />
<input type = "submit" value = "Submit Data" />
</form>
</body>
</html>

 Creating Forms and HTML

CGI contains a huge number of methods used to create HTML. You will find one method per tag. In
order to enable these methods, you must create a CGI object by calling CGI.new.

To make tag 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 tag. For example −

#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cgi.out {
cgi.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
}
}
}
}

NOTE − The form method of the CGI class can accept a method parameter, which will set the HTTP
method ( GET, POST, and so on...) to be used on form submittal. The default, used in this example, is
POST.

This will produce the following result −

Content-Type: text/html
Content-Length: 302

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 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 COLS = "70" NAME = "get_text" ROWS =
"10"></TEXTAREA>
<BR>
<INPUT TYPE = "submit">
</FORM>
</BODY>
</HTML>

 Quoting Strings

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.

For example, any / in the query portion of the URL will be translated to the string %2F and must be
translated back to a / for you to use it. Space and ampersand are also special characters. To handle this,
CGI provides the routines CGI.escape and CGI.unescape.

#!/usr/bin/ruby

require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl")

This will produce the following result −

Zara+Ali%2FA Sweet+%26+Sour+Girl")

#!/usr/bin/ruby

require 'cgi'
puts CGI.escapeHTML('<h1>Zara Ali/A Sweet & Sour Girl</h1>')

This will produce the following result −

&lt;h1&gt;Zara Ali/A Sweet & Sour Girl&lt;/h1&gt;'


1.2.2 Cookies

HTTP protocol is a stateless protocol. But for a commercial website, it is required to maintain session
information among different pages. For example, one user registration ends after completing many
pages. But how to maintain user's session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor experience or
site statistics.

 How It Works?

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept
the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor
arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server
knows/remembers what was stored.

Cookies are a plain text data record of five variable-length fields −

 Expires − The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.
 Domain − The domain name of your site.
 Path − The path to the directory or web page that sets the cookie. This may be blank if you
want to retrieve the cookie from any directory or page.
 Secure − If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
 Name = Value − Cookies are set and retrieved in the form of key and value pairs.

 Handling Cookies in Ruby

You can create a named cookie object and store any textual information in it. To send it down to the
browser, set a cookie header in the call to CGI.out.

#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cookie = CGI::Cookie.new('name' => 'mycookie', 'value' =>
'Zara Ali', 'expires' => Time.now + 3600)
cgi.out('cookie' => cookie) do
cgi.head + cgi.body { "Cookie stored" }
end

The next time the user comes back to this page, you can retrieve the cookie values set as shown below

#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cookie = cgi.cookies['mycookie']
cgi.out('cookie' => cookie) do
cgi.head + cgi.body { cookie[0] }
end

Cookies are represented using a separate object of class CGI::Cookie, containing the following
accessors −

Attribute Returned Value

name Cookie name

value An array of cookie values

path The cookie's path

domain The domain

expires The expiration time (as a Time object)

secure True if secure cookie

Following is the syntax for setting cookies −

# Set a simple session cookie


cookies[:user_name] = "david"

# Set a cookie that expires in 1 hour


cookies[:login] = { :value => "XJ12", :expires => Time.now +
3600}

Following is the syntax for reading cookies −


cookies[:user_name] # => "david"
cookies.size # => 2

Following is the syntax for deleting cookies −

cookies.delete :user_name

All the option symbols for setting cookies are −

 value − The cookie.s value or list of values (as an array).


 path − The path for which this cookie applies. Defaults to the root of the application.
 domain − The domain for which this cookie applies.
 expires − The time at which this cookie expires, as a +Time+ object.
 secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies are
only transmitted to HTTPS servers.

1.2.3 Choice of Webservers


Web Server: Web server is a program which processes the network requests of the users and serves
them with files that create web pages. This exchange takes place using Hypertext Transfer Protocol
(HTTP).
Basically, web servers are computers used to store HTTP files which makes a website and when a
client requests a certain website, it delivers the requested website to the client. For example, you
want to open Facebook on your laptop and enter the URL in the search bar of google. Now, the
laptop will send an HTTP request to view the facebook webpage to another computer known as the
webserver. This computer (webserver) contains all the files (usually in HTTP format) which make
up the website like text, images, gif files, etc. After processing the request, the webserver will send
the requested website-related files to your computer and then you can reach the website.
Different websites can be stored on the same or different web servers but that doesn’t affect the
actual website that you are seeing in your computer. The web server can be any software or hardware
but is usually a software running on a computer. One web server can handle multiple users at any
given time which is a necessity otherwise there had to be a web server for each user and considering
the current world population, is nearly close to impossible. A web server is never disconnected from
the internet because if it was, then it won’t be able to receive any requests, and therefore cannot
process them.
There are many web servers available in the market both free and paid. Some of them are described
below:

 Apache HTTP server: It is the most popular web server and about 60 percent of the world’s
web server machines run this web server. The Apache HTTP web server was developed by the
Apache Software Foundation. It is an open-source software which means that we can access and
make changes to its code and mold it according to our preference. The Apache Web Server can
be installed and operated easily on almost all operating systems like Linux, MacOS, Windows,
etc.

 Microsoft Internet Information Services (IIS): IIS (Internet Information Services) is a high
performing web server developed by Microsoft. It is strongly united with the operating system
and is therefore relatively easier to administer. It is developed by Microsoft, it has a good
customer support system which is easier to access if we encounter any issue with the server. It
has all the features of the Apache HTTP Server except that it is not an open-source software and
therefore its code is inaccessible which means that we cannot make changes in the code to suit
our needs. It can be easily installed in any Windows device.
 Lighttpd: Lighttpd is pronounced as ‘Lightly’. It currently runs about 0.1 percent of the world’s
websites. Lighttpd has a small CPU load and is therefore comparatively easier to run. It has a
low memory footprint and hence in comparison to the other web servers, requires less memory
space to run which is always an advantage. It also has speed optimizations which means that we
can optimize or change its speed according to our requirements. It is an open-source software
which means that we can access its code and add changes to it according to our needs and then
upload our own module (the changed code).

 Jigsaw Server: Jigsaw has been written in the Java language and it can run CGI (common
gateway interference) scripts as well as PHP programs. It is not a full-fledged server and was
developed as an experimental server to demonstrate the new web protocols. It is an open-source
software which means that we can access its code and add changes to it according to our needs
and then upload our own module (the changed code). It can be installed on any device provided
that the device supports Java language and modifications in Java.
 Sun Java System: The Sun Java System supports various languages, scripts, and technologies
required for Web 2.0 such as Python, PHP, etc. It is not an open-source software and therefore
its code is inaccessible which means that we cannot make changes in the code to suit our needs.

1.2.4 SOAP and Webservices

SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for
exchanging information among computers. SOAP is an application of the XML specification.

 SOAP is a communication protocol designed to communicate via Internet.


 SOAP can extend HTTP for XML messaging.
 SOAP provides data transport for Web services.
 SOAP can exchange complete documents or call a remote procedure.
 SOAP can be used for broadcasting a message.
 SOAP is platform- and language-independent.
 SOAP is the XML way of defining what information is sent and how.
 SOAP enables client applications to easily connect to remote services and invoke remote
methods.

Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of
transport protocols, the initial focus of SOAP is remote procedure calls transported via HTTP.

Other frameworks including CORBA, DCOM, and Java RMI provide similar functionality to SOAP,
but SOAP messages are written entirely in XML and are therefore uniquely platform- and language-
independent.

It uses XML to encode the information that makes the remote procedure call, and HTTP to transport
that information across a network from clients to servers and vice versa.
SOAP has several advantages over other technologies like COM, CORBA etc: for example, its
relatively cheap deployment and debugging costs, its extensibility and ease-of-use, and the existence
of several implementations for different languages and platforms.

Installing SOAP4R

SOAP4R is the SOAP implementation for Ruby developed by Hiroshi Nakamura and can be
downloaded from −

NOTE − There may be a great chance that you already have installed this component.

If you are aware of gem utility then you can use the following command to install SOAP4R and related
packages.

$ gem install soap4r --include-dependencies

If you are working on Windows, then you need to download a zipped file from the above location and
need to install it using the standard installation method by running ruby install.rb.

Writing SOAP4R Servers

SOAP4R supports two different types of servers −

 CGI/FastCGI based (SOAP::RPC::CGIStub)


 Standalone (SOAP::RPC:StandaloneServer)

This chapter gives detail on writing a stand alone server. The following steps are involved in writing a
SOAP server.

Step 1 - Inherit SOAP::RPC::StandaloneServer Class

To implement your own stand alone server you need to write a new class, which will be child
of SOAP::StandaloneServer as follows −

class MyServer < SOAP::RPC::StandaloneServer


...............
end

NOTE − If you want to write a FastCGI based server then you need to take SOAP::RPC::CGIStub as
parent class, rest of the procedure will remain the same.
Step 2 - Define Handler Methods

Second step is to write your Web Services methods, which you would like to expose to the outside
world.

They can be written as simple Ruby methods. For example, let's write two methods to add two numbers
and divide two numbers −

class MyServer < SOAP::RPC::StandaloneServer


...............

# Handler methods
def add(a, b)
return a + b
end
def div(a, b)
return a / b
end
end
Step 3 - Expose Handler Methods

Next step is to add our defined methods to our server. The initialize method is used to expose service
methods with one of the two following methods −

class MyServer < SOAP::RPC::StandaloneServer


def initialize(*args)
add_method(receiver, methodName, *paramArg)
end
end

Here is the description of the parameters −

Sr.No. Parameter & Description

receiver
1
The object that contains the methodName method. You define the service methods in
the same class as the methodDef method, this parameter is self.

2 methodName
The name of the method that is called due to an RPC request.

3 paramArg
Specifies, when given, the parameter names and parameter modes.
To understand the usage of inout or out parameters, consider the following service method that takes
two parameters (inParam and inoutParam), returns one normal return value (retVal) and two further
parameters: inoutParam and outParam −

def aMeth(inParam, inoutParam)


retVal = inParam + inoutParam
outParam = inParam . inoutParam
inoutParam = inParam * inoutParam
return retVal, inoutParam, outParam
end

Now, we can expose this method as follows −

add_method(self, 'aMeth', [
%w(in inParam),
%w(inout inoutParam),
%w(out outParam),
%w(retval return)
])
Step 4 - Start the Server

The final step is to start your server by instantiating one instance of the derived class and
calling start method.

myServer = MyServer.new('ServerName',
'urn:ruby:ServiceName', hostname, port)

myServer.start

Here is the description of required parameters −

Sr.No. Parameter & Description

1 ServerName
A server name, you can give what you like most.

2 urn:ruby:ServiceName
Here urn:ruby is constant but you can give a unique ServiceName name for this server.

3 hostname
Specifies the hostname on which this server will listen.

4 port
An available port number to be used for the web service.
 Example

Now, using the above steps, let us write one standalone server −

require "soap/rpc/standaloneserver"

begin
class MyServer < SOAP::RPC::StandaloneServer

# Expose our services


def initialize(*args)
add_method(self, 'add', 'a', 'b')
add_method(self, 'div', 'a', 'b')
end

# Handler methods
def add(a, b)
return a + b
end
def div(a, b)
return a / b
end
end
server = MyServer.new("MyServer",
'urn:ruby:calculation', 'localhost', 8080)
trap('INT){
server.shutdown
}
server.start
rescue => err
puts err.message
end

When executed, this server application starts a standalone SOAP server on localhost and listens for
requests on port 8080. It exposes one service methods, add and div, which takes two parameters and
return the result.

Now, you can run this server in background as follows −

$ ruby MyServer.rb&
1.3 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 has the unique distinction of being the only cross-platform GUI. Tk runs on Windows, Mac, and
Linux and provides a native look-and-feel on each operating system.

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, and those widgets within another widget, ad infinitum. 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.

 Most Tk-based applications follow the same cycle: create the widgets, place them in the
interface, and finally, bind the events associated with each widget to a method.
 There are three geometry managers; place, grid and pack that are responsible for controlling
the size and location of each of the widgets in the interface.

 Installation

The Ruby Tk bindings are distributed with Ruby but Tk is a separate installation. Windows users can
download a single click Tk installation from ActiveState's ActiveTcl.

Mac and Linux users may not need to install it because there is a great chance that its already installed
along with OS but if not, you can download prebuilt packages or get the source from the Tcl Developer
Xchange.

1.3.1 Simple Tk Application

A typical structure for Ruby/Tk programs is to create the main or root window (an instance of TkRoot),
add widgets to it to build up the user interface, and then start the main event loop by
calling Tk.mainloop.

The traditional Hello, World! example for Ruby/Tk looks something like this −

require 'tk'

root = TkRoot.new { title "Hello, World!" }


TkLabel.new(root) do
text 'Hello, World!'
pack { padx 15 ; pady 15; side 'left' }
end
Tk.mainloop

Here, after loading the tk extension module, we create a root-level frame using TkRoot.new. We then
make a TkLabel widget as a child of the root frame, setting several options for the label. Finally, we
pack the root frame and enter the main GUI event loop.

If you would run this script, it would produce the following result −

1.3.2 Widgets

 Ruby/Tk Widget Classes

There is a list of various Ruby/Tk classes, which can be used to create a desired GUI using Ruby/Tk.

 TkFrame Creates and manipulates frame widgets.


 TkButton Creates and manipulates button widgets.
 TkLabel Creates and manipulates label widgets.
 TkEntry Creates and manipulates entry widgets.
 TkCheckButton Creates and manipulates checkbutton widgets.
 TkRadioButton Creates and manipulates radiobutton widgets.
 TkListbox Creates and manipulates listbox widgets.
 TkComboBox Creates and manipulates listbox widgets.
 TkMenu Creates and manipulates menu widgets.
 TkMenubutton Creates and manipulates menubutton widgets.
 Tk.messageBox Creates and manipulates a message dialog.
 TkScrollbar Creates and manipulates scrollbar widgets.
 TkCanvas Creates and manipulates canvas widgets.
 TkScale Creates and manipulates scale widgets.
 TkText Creates and manipulates text widgets.
 TkToplevel Creates and manipulates toplevel widgets.
 TkSpinbox Creates and manipulates Spinbox widgets.
 TkProgressBar Creates and manipulates Progress Bar widgets.
 Dialog Box Creates and manipulates Dialog Box widgets.
 Tk::Tile::Notebook Display several windows in limited space with notebook metaphor.
 Tk::Tile::Paned Displays a number of subwindows, stacked either vertically or
horizontally.
 Tk::Tile::Separator Displays a horizontal or vertical separator bar.
 Ruby/Tk Font, Colors and Images Understanding Ruby/Tk Fonts, Colors and Images

 Standard Configuration Options

All widgets have a number of different configuration options, which generally control how they are
displayed or how they behave. The options that are available depend upon the widget class of course.

Here is a list of all the standard configuration options, which could be applicable to any Ruby/Tk
widget.

There are other widget specific options also, which would be explained along with widgets.

 Widget Specific Options

Sr.No. Options & Description

background => String


This option is the same as the standard background option except that its value may
1 also be specified as an undefined value. In this case, the widget will display no
background or border, and no colors will be consumed from its colormap for its
background and border.

colormap => String

2 Specifies a colormap to use for the window. The value may be either new, in which
case a new colormap is created for the window and its children, or the name of another
window (which must be on the same screen ), in which case the new window will use
the colormap from the specified window. If the colormap option is not specified, the
new window uses the same colormap as its parent.

container => Boolean


The value must be a boolean. If true, it means that this window will be used as a
3 container in which some other application will be embedded. The window will support
the appropriate window manager protocols for things like geometry requests. The
window should not have any children of its own in this application.

4 height => Integer


Specifies the desired height for the window in pixels or points.

5
width => Integer
Specifies the desired width for the window in pixels or points.

1.3.3 Binding events

When a new frame is created, it has no default event bindings: frames are not intended to be interactive.

 Examples

require "tk"

f1 = TkFrame.new {
relief 'sunken'
borderwidth 3
background "red"
padx 15
pady 20
pack('side' => 'left')
}
f2 = TkFrame.new {
relief 'groove'
borderwidth 1
background "yellow"
padx 10
pady 10
pack('side' => 'right')
}

TkButton.new(f1) {
text 'Button1'
command {print "push button1!!\n"}
pack('fill' => 'x')
}
TkButton.new(f1) {
text 'Button2'
command {print "push button2!!\n"}
pack('fill' => 'x')
}
TkButton.new(f2) {
text 'Quit'
command 'exit'
pack('fill' => 'x')
}
Tk.mainloop

This will produce the following result −

Ruby/Tk supports event loop, which receives events from the operating system. These are things like
button presses, keystrokes, mouse movement, window resizing, and so on.

Ruby/Tk takes care of managing this event loop for you. It will figure out what widget the event applies
to (did the user click on this button? if a key was pressed, which textbox had the focus?), and dispatch
it accordingly. Individual widgets know how to respond to events, so for example a button might
change color when the mouse moves over it, and revert back when the mouse leaves.

At a higher level, Ruby/Tk invokes callbacks in your program to indicate that something significant
happened to a widget For either case, you can provide a code block or a Ruby Proc object that specifies
how the application responds to the event or callback.

Let's take a look at how to use the bind method to associate basic window system events with the Ruby
procedures that handle them. The simplest form of bind takes as its inputs a string indicating the event
name and a code block that Tk uses to handle the event.
For example, to catch the ButtonRelease event for the first mouse button on some widget, you'd write

someWidget.bind('ButtonRelease-1')
{
....code block to handle this event...
}

An event name can include additional modifiers and details. A modifier is a string
like Shift, Control or Alt, indicating that one of the modifier keys was pressed.

So, for example, to catch the event that's generated when the user holds down the Ctrl key and clicks
the right mouse button.

someWidget.bind('Control-ButtonPress-3', proc { puts "Ouch!"


})

Many Ruby/Tk widgets can trigger callbacks when the user activates them, and you can use
the command callback to specify that a certain code block or procedure is invoked when that happens.
As seen earlier, you can specify the command callback procedure when you create the widget −

helpButton = TkButton.new(buttonFrame) {
text "Help"
command proc { showHelp }
}

Or you can assign it later, using the widget's command method −

helpButton.command proc { showHelp }

Since the command method accepts either procedures or code blocks, you could also write the previous
code example as −

helpButton = TkButton.new(buttonFrame) {
text "Help"
command { showHelp }
}
You can use the following basic event types in your Ruby/Tk application −

 The configure Method

The configure method can be used to set and retrieve any widget configuration values. For example,
to change the width of a button you can call configure method any time as follows −
require "tk"

button = TkButton.new {
text 'Hello World!'
pack
}
button.configure('activebackground', 'blue')
Tk.mainloop

To get the value for a current widget, just supply it without a value as follows −

color = button.configure('activebackground')

You can also call configure without any options at all, which will give you a listing of all options and
their values.

 The cget Method

For simply retrieving the value of an option, configure returns more information than you generally
want. The cget method returns just the current value.

color = button.cget('activebackground')

1.3.4 Canvas

A Canvas widget implements structured graphics. A canvas displays any number of items, which may
be things like rectangles, circles, lines, and text.

Items may be manipulated (e.g., moved or re-colored) and callbacks may be associated with items in
much the same way that the bind method allows callbacks to be bound to widgets.

 Syntax

Here is a simple syntax to create this widget −

TkCanvas.new {
.....Standard Options....
.....Widget-specific Options....
}
 Standard Options

 background
 borderwidth
 cursor
 highlightbackground
 highlightcolor
 highlightthickness
 relief
 selectbackground
 selectborderwidth
 selectforeground
 state
 takefocus
 tile
 xscrollcommand
 yscrollcommand

 Widget Specific Options

Sr.No. Options & Description

closeenough =>Integer
1 Specifies a floating-point value indicating how close the mouse cursor must be to an
item before it is considered to be inside the item. Defaults to 1.0.

confine =>Boolean

2 Specifies a boolean value that indicates whether or not it should be allowable to set the
canvas's view outside the region defined by the scrollregion argument. Defaults to true,
which means that the view will be constrained within the scroll region.

height =>Integer
3 Specifies a desired window height that the canvas widget should request from its
geometry manager.
scrollregion =>Coordinates

4 Specifies a list with four coordinates describing the left, top, right, and bottom
coordinates of a rectangular region. This region is used for scrolling purposes and is
considered to be the boundary of the information in the canvas.

state =>String

5 Modifies the default state of the canvas where state may be set to one of: normal,
disabled, or hidden. Individual canvas objects all have their own state option, which
overrides the default state.

width =>Integer
6 Specifies a desired window width that the canvas widget should request from its
geometry manager.

xscrollincrement =>Integer
Specifies an increment for horizontal scrolling, in any of the usual forms permitted for

7 screen distances. If the value of this option is greater than zero, the horizontal view in
the window will be constrained so that the canvas x coordinate at the left edge of the
window is always an even multiple of xscrollincrement; furthermore, the units for
scrolling will also be xscrollincrement.

yscrollincrement =>Integer
Specifies an increment for vertical scrolling, in any of the usual forms permitted for

8 screen distances. If the value of this option is greater than zero, the vertical view in the
window will be constrained so that the canvas y coordinate at the top edge of the
window is always an even multiple of yscrollincrement; furthermore, the units for
scrolling will also be yscrollincrement.

 Indices

Indices are used for methods such as inserting text, deleting a range of characters, and setting the
insertion cursor position. An index may be specified in any of a number of ways, and different types
of items may support different forms for specifying indices.

Text items support the following forms for an index −

 number − A decimal number giving the position of the desired character within the text item.
0 refers to the first character, 1 to the next character, and so on.
 end − Refers to the character or coordinate just after the last one in the item (same as the
number of characters or coordinates in the item).
 insert − Refers to the character just before which the insertion cursor is drawn in this item. Not
valid for lines and polygons.

 Creating Items

When you create a new canvas widget, it will essentially be a large rectangle with nothing on it; truly
a blank canvas in other words. To do anything useful with it, you'll need to add items to it.

There are a wide variety of different types of items you can add. Following methods will be used to
create different items inside a canvas −

 Arc Items

Items of type arc appear on the display as arc-shaped regions. An arc is a section of an oval delimited
by two angles. Arcs are created with methods of the following form −

The TkcArc.new(canvas, x1, y1, x2, y2, ?option, value, option, value, ...?) method will be used to
create an arc.

The arguments x1, y1, x2, and y2 give the coordinates of two diagonally opposite corners of a
rectangular region enclosing the oval that defines the arc. Here is the description of other options −

 extent => degrees − Specifies the size of the angular range occupied by the arc. If it is greater
than 360 or less than -360, then degrees modulo 360 is used as the extent.
 fill => color − Fills the region of the arc with color.
 outline => color − Color specifies a color to use for drawing the arc's outline.
 start => degrees − Specifies the beginning of the angular range occupied by the arc.
 style => type − Specifies how to draw the arc. If type is pieslice (the default) then the arc's
region is defined by a section of the oval's perimeter plus two line segments, one between the
center of the oval and each end of the perimeter section. If type is chord then the arc's region
is defined by a section of the oval's perimeter plus a single line segment connecting the two
end points of the perimeter section. If type is arc then the arc's region consists of a section of
the perimeter alone.
 tags => tagList − Specifies a set of tags to apply to the item. TagList consists of a list of tag
names, which replace any existing tags for the item. TagList may be an empty list.
 width => outlineWidth − Specifies the width of the outline to be drawn around the arc's
region.
 Bitmap Items

Items of type bitmap appear on the display as images with two colors, foreground and background.
Bitmaps are created with methods of the following form −

The TkcBitmap.new(canvas, x, y, ?option, value, option, value, ...?) method will be used to create
a bitmap.

The arguments x and y specify the coordinates of a point used to position the bitmap on the display.
Here is the description of other options −

 anchor => anchorPos − AnchorPos tells how to position the bitmap relative to the positioning
point for the item. For example, if anchorPos is center then the bitmap is centered on the point;
if anchorPos is n then the bitmap will be drawn so that its top center point is at the positioning
point. This option defaults to center.
 background => color − Specifies a color to use for each of the bitmap pixels whose value is
0.
 bitmap => bitmap − Specifies the bitmap to display in the item.
 foreground => color − Specifies a color to use for each of the bitmap pixels whose value is 1.
 tags => tagList − Specifies a set of tags to apply to the item. TagList consists of a list of tag
names, which replace any existing tags for the item. TagList may be an empty list.
 Image Items

Items of type image are used to display images on a canvas. Images are created with methods of the
following form: :

The TkcImage.new(canvas,x, y, ?option, value, option, value, ...?) method will be used to create an
image.

The arguments x and y specify the coordinates of a point used to position the image on the display.
Here is the description of other options −

 anchor => anchorPos − AnchorPos tells how to position the bitmap relative to the positioning
point for the item. For example, if anchorPos is center then the bitmap is centered on the point;
if anchorPos is n then the bitmap will be drawn so that its top center point is at the positioning
point. This option defaults to center.
 image => name − Specifies the name of the image to display in the item. This image must have
been created previously with the image create command.
 tags => tagList − Specifies a set of tags to apply to the item. TagList consists of a list of tag
names, which replace any existing tags for the item. TagList may be an empty list.
 Line Items

Items of type line appear on the display as one or more connected line segments or curves. Lines are
created with methods of the following form −

The TkcLine.new(canvas, x1, y1..., xn, yn, ?option, value, ...?) method will be used to create a line.

The arguments x1 through yn give the coordinates for a series of two or more points that describe a
series of connected line segments. Here is the description of other options −

 arrow => where − Indicates whether or not arrowheads are to be drawn at one or both ends of
the line. Where must have one of the values none (for no arrowheads), first (for an arrowhead
at the first point of the line), last (for an arrowhead at the last point of the line), or both (for
arrowheads at both ends). This option defaults to none.
 arrowshape => shape − This option indicates how to draw arrowheads. If this option isn't
specified then Tk picks a reasonable shape.
 dash => pattern − Specifies a pattern to draw the line.
 capstyle => style − Specifies the ways in which caps are to be drawn at the endpoints of the
line. Possible values are butt, projecting, or round.
 fill => color − Color specifies a color to use for drawing the line.
 joinstyle => style − Specifies the ways in which joints are to be drawn at the vertices of the
line. Possible values are bevel, miter, or round.
 smooth => boolean − It indicates whether or not the line should be drawn as a curve.
 splinesteps => number − Specifies the degree of smoothness desired for curves: each spline
will be approximated with number line segments. This option is ignored unless
the smooth option is true.
 stipple => bitmap − Indicates that the line should be filled in a stipple pattern; bitmap specifies
the stipple pattern to use.
 tags => tagList − Specifies a set of tags to apply to the item. TagList consists of a list of tag
names, which replace any existing tags for the item. TagList may be an empty list.
 width => lineWidth − Specifies the width of the line.
 Rectangle Items

Items of type rectangle appear as rectangular regions on the display. Each rectangle may have an
outline, a fill, or both. Rectangles are created with methods of the following form −

The TkcRectangle.new(canvas, x1, y1, x2, y2, ?option, value,...?) method will be used to create a
Rectangle.

The arguments x1, y1, x2, and y2 give the coordinates of two diagonally opposite corners of the
rectangle. Here is the description of other options −

 fill => color − Fills the area of the rectangle with color.
 outline => color − Draws an outline around the edge of the rectangle in color.
 stipple => bitmap − Indicates that the rectangle should be filled in a stipple pattern; bitmap
specifies the stipple pattern to use.
 tags => tagList − Specifies a set of tags to apply to the item. TagList consists of a list of tag
names, which replace any existing tags for the item. TagList may be an empty list.
 width => outlineWidth − Specifies the width of the outline to be drawn around the rectangle.

 Event Bindings

Canvas has the default bindings to allow scrolling if necessary: <Up>, <Down>, <Left> and <Right>
(and their <Control-*> counter parts). Further <Prior>, <Next>, <Home> and <End>. These bindings
allow you to navigate the same way as in other widgets that can scroll.

 Example 1
require "tk"

canvas = TkCanvas.new
TkcRectangle.new(canvas, '1c', '2c', '3c', '3c', 'outline'
=> 'black', 'fill' => 'blue')
TkcLine.new(canvas, 0, 0, 100, 100, 'width' => '2', 'fill'
=> 'red')
canvas.pack

Tk.mainloop

This will produce the following result −


 Example 2

require 'tk'

root = TkRoot.new
root.title = "Window"

canvas = TkCanvas.new(root) do
place('height' => 170, 'width' => 100, 'x' => 10, 'y' =>
10)
end

TkcLine.new(canvas, 0, 5, 100, 5)
TkcLine.new(canvas, 0, 15, 100, 15, 'width' => 2)
TkcLine.new(canvas, 0, 25, 100, 25, 'width' => 3)
TkcLine.new(canvas, 0, 35, 100, 35, 'width' => 4)
TkcLine.new(canvas, 0, 55, 100, 55, 'width' => 3, 'dash' =>
".")
TkcLine.new(canvas, 0, 65, 100, 65, 'width' => 3, 'dash' =>
"-")
TkcLine.new(canvas, 0, 75, 100, 75, 'width' => 3, 'dash' =>
"-.")
TkcLine.new(canvas, 0, 85, 100, 85, 'width' => 3, 'dash' =>
"-..")
TkcLine.new(canvas, 0, 105, 100, 105, 'width' => 2, 'arrow'
=> "first")
TkcLine.new(canvas, 0, 115, 100, 115, 'width' => 2, 'arrow'
=> "last")
TkcLine.new(canvas, 0, 125, 100, 125, 'width' => 2, 'arrow'
=> "both")
TkcLine.new(canvas, 10, 145, 90, 145, 'width' => 15,
'capstyle' => "round")
Tk.mainloop

This will produce the following result −


 Example 3
require 'tk'

root = TkRoot.new
root.title = "Window"

canvas = TkCanvas.new(root) do
place('height' => 170, 'width' => 100, 'x' => 10, 'y' =>
10)
end

TkcRectangle.new(canvas, 10, 5, 55, 50, 'width' => 1)


TkcRectangle.new(canvas, 10, 65, 55, 110, 'width' => 5)
TkcRectangle.new(canvas, 10, 125, 55, 170, 'width' => 1,
'fill' => "red")

Tk.mainloop

This will produce the following result −

 Example 4
require 'tk'
root = TkRoot.new
root.title = "Window"

canvas = TkCanvas.new(root) do
place('height' => 170, 'width' => 100, 'x' => 10, 'y' =>
10)
end

TkcLine.new(canvas, 0, 10, 100, 10, 'width' => 10, 'fill'


=> "blue")
TkcLine.new(canvas, 0, 30, 100, 30, 'width' => 10, 'fill'
=> "red")
TkcLine.new(canvas, 0, 50, 100, 50, 'width' => 10, 'fill'
=> "green")
TkcLine.new(canvas, 0, 70, 100, 70, 'width' => 10, 'fill'
=> "violet")
TkcLine.new(canvas, 0, 90, 100, 90, 'width' => 10, 'fill'
=> "yellow")
TkcLine.new(canvas, 0, 110, 100, 110, 'width' => 10, 'fill'
=> "pink")
TkcLine.new(canvas, 0, 130, 100, 130, 'width' => 10, 'fill'
=> "orange")
TkcLine.new(canvas, 0, 150, 100, 150, 'width' => 10, 'fill'
=> "grey")
Tk.mainloop

This will produce the following result −

1.3.5 Scrolling

A Scrollbar helps the user to see all parts of another widget, whose content is typically much larger
than what can be shown in the available screen space.
A scrollbar displays two arrows, one at each end of the scrollbar, and a slider in the middle portion of
the scrollbar. The position and size of the slider indicate which portion of the document is visible in
the associated window.

 Syntax

Here is a simple syntax to create this widget −TkScrollbar.new {

.....Standard Options....
.....Widget-specific Options....
}

 Standard Options

 activebackground
 highlightbackground
 orient
 takefocus
 background
 highlightcolor
 relief
 troughcolor
 borderwidth
 highlightthickness
 repeatdelay
 cursor
 jump
 repeatinterval

 Widget Specific Options

Sr.No. Options & Description

activerelief => String


1 Specifies the relief to use when displaying the element that is active, if any.
Elements other than the active element are always displayed with a raised
relief.
command => String
2 Specifies a callback to invoke to change the view in the widget associated
with the scrollbar. When a user requests a view change by manipulating the
scrollbar, the callback is invoked.

elementborderwidth => Integer


3 Specifies the width of borders drawn around the internal elements of the
scrollbar.

width => Integer


4 Specifies the desired narrow dimension of the scrollbar window, not including
3-D border, if any. For vertical scrollbars this will be the width and for
horizontal scrollbars this will be the height.

 Elements of Scrollbar

A scrollbar displays five elements, which are referred in the methods for the scrollbar −

 arrow1 − The top or left arrow in the scrollbar.


 trough1 − The region between the slider and arrow1.
 slider − The rectangle that indicates what is visible in the associated widget.
 trough2 − The region between the slider and arrow2.
 arrow2 − The bottom or right arrow in the scrollbar.

 Manipulating Scrollbar

The following useful methods to manipulate the content of a scrollbar −

 activate(?element?) − Marks the element indicated by element as active, which causes it to be


displayed as specified by the activebackground and activerelief options. The only element
values understood by this command are arrow1, slider, or arrow2.
 delta(deltaX, deltaY) − Returns a real number indicating the fractional change in the scrollbar
setting that corresponds to a given change in slider position.
 fraction(x, y) − Returns a real number between 0 and 1 indicating where the point given by x
and y lies in the trough area of the scrollbar. The value 0 corresponds to the top or left of the
trough, the value 1 corresponds to the bottom or right, 0.5 corresponds to the middle, and so
on.
 get − Returns the scrollbar settings in the form of a list whose elements are the arguments to
the most recent set method.
 identify(x, y) − Returns the name of the element under the point given by x and y (such as
arrow1), or an empty string if the point does not lie in any element of the scrollbar. X and y
must be pixel coordinates relative to the scrollbar widget.
 set(first, last) − This command is invoked by the scrollbar's associated widget to tell the
scrollbar about the current view in the widget. The command takes two arguments, each of
which is a real fraction between 0 and 1. The fractions describe the range of the document that
is visible in the associated widget.

 Event Bindings

Ruby/Tk automatically creates class bindings for scrollbars that gives them the following default
behavior. If the behavior is different for vertical and horizontal scrollbars, the horizontal behavior is
described in parentheses −

 Pressing button 1 over arrow1 causes the view in the associated widget to shift up (left) by one
unit so that the document appears to move down (right) one unit. If the button is held down,
the action auto-repeats.
 Pressing button 1 over trough1 causes the view in the associated widget to shift up (left) by one
screenful so that the document appears to move down (right) one screenful. If the button is held
down, the action auto-repeats.
 Pressing button 1 over the slider and dragging causes the view to drag with the slider. If the
jump option is true, then the view doesn't drag along with the slider; it changes only when the
mouse button is released.
 Pressing button 1 over trough2 causes the view in the associated widget to shift down (right)
by one screenful so that the document appears to move up (left) one screenful. If the button is
held down, the action auto-repeats.
 Pressing button 1 over arrow2 causes the view in the associated widget to shift down (right) by
one unit so that the document appears to move up (left) one unit. If the button is held down, the
action auto-repeats.
 If button 2 is pressed over the trough or the slider, it sets the view to correspond to the mouse
position; dragging the mouse with button 2 down causes the view to drag with the mouse. If
button 2 is pressed over one of the arrows, it causes the same behavior as pressing button 1.
 If button 1 is pressed with the Control key down, then if the mouse is over arrow1 or trough1
the view changes to the very top (left) of the document; if the mouse is over arrow2 or trough2
the view changes to the very bottom (right) of the document; if the mouse is anywhere else
then the button press has no effect.
 In vertical scrollbars the Up and Down keys have the same behavior as mouse clicks over
arrow1 and arrow2, respectively. In horizontal scrollbars these keys have no effect.
 In vertical scrollbars Control-Up and Control-Down have the same behavior as mouse clicks
over trough1 and trough2, respectively. In horizontal scrollbars these keys have no effect.
 In horizontal scrollbars the Up and Down keys have the same behavior as mouse clicks over
arrow1 and arrow2, respectively. In vertical scrollbars these keys have no effect.
 In horizontal scrollbars Control-Up and Control-Down have the same behavior as mouse clicks
over trough1 and trough2, respectively. In vertical scrollbars these keys have no effect.
 The Prior and Next keys have the same behavior as mouse clicks over trough1 and trough2,
respectively.
 The Home key adjusts the view to the top (left edge) of the document.
 The End key adjusts the view to the bottom (right edge) of the document.
 Examples
require "tk"

list = scroll = nil

list = TkListbox.new {
yscroll proc{|idx|
scroll.set *idx
}
width 20
height 16
setgrid 1
pack('side' => 'left', 'fill' => 'y', 'expand' => 1)
}
scroll = TkScrollbar.new {
command proc{|idx|
list.yview *idx
}
pack('side' => 'left', 'fill' => 'y', 'expand' => 1)
}

for f in Dir.glob("*")
list.insert 'end', f
end

Tk.mainloop

This will produce the following result −

You might also like