S.L UNIT-I
S.L UNIT-I
RUBY 20.12.2024
UNIT-I
Introduction
Ruby, Rail , The structure and Execution of Ruby Programs, Package Management with
RUBYGEMS, Ruby and web: Writing scripts, cookies Choice web services, SOAP and
webservices,
Ruby Tk - Simple Tk Application, widgets Binding events, Caracolling
Compiler vs Interpreter
A compiler takes entire program and converts it into object code which is typically
stored in a file. The object code is also referred as binary code and can be directly
executed by the machine after linking. Examples of compiled programming languages
are C and C++.
An Interpreter directly executes instructions written in a a pro programming or scripting
language without previously converting them to an object code or machine code.
Examples of interpreted languages are Perl, Python and Matlab.
Following are some interesting facts about interpreters and compilers.
1. Both compilers and interpreters convert source code (text files) into tokens, both may
generate a parse tree, and both may generate immediate instructions. The basic
difference is that a compiler system, including a (built in or separate) linker, generates
a stand alone machine code program, while an interpreter system instead performs the
actions described by the high level program.
2. Once a program is compiled, its source code is not useful for running the code. For
interpreted programs, the source code is needed to run the program every time.
3. In general, interpreted programs run slower than the compiled programs.
4. Java programs are first compiled to an intermediate form, then interpreted by the
interpreter.
Server-side Scripting
It helps work with the back end.
It doesn't depend on the client.
It helps provide a response to every request that comes in from the user/client.
It runs on the web server.
It requires the interaction with the server for the data to be process.
Server side scripting languages such as PHP,ASP.net, ColdFusion, Python, Ruby on
Rails.
It is considered to be a secure way of working with applications.
It can be used to customize web pages.
It can also be used to provide dynamic websites.
Client-side Scripting
It helps work with the front end.
It is visible to the users.
The scripts are run on the client browser.
It runs on the user/client's computer.
It depends on the browser's version
It doesn't interact with the server to process data.
Client side scripting involves languages such as HTML, CSS, JavaScript.
It helps reduce the load on the server.
It is considered to be less secure in comparison to client side scripting.
INTRODUCTION TO RUBY
Ruby is a pure object-oriented programming language. It was created in 1993 Japan by
Yukihiro Matsumoto, also known as Matz.
Ruby is "A Programmer's Best Friend".
Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python,
and Smalltalk are scripting languages.
Smalltalk is a true object-oriented language.
Ruby, like Smalltalk, is a perfect object-oriented language.
Using Ruby syntax is much easier than using Smalltalk syntax.
Features of Ruby
Ruby is an open-source and is freely available on the Webe
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.
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.
Ruby can be installed in Windows and Linux environments. Ruby support many GUI
tools such as Tcl.
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.
Ruby is being used in wide range of fields, especially in Web Applications and data
science.
Ruby is a dynamic programming language therefore, it does not have hard rules on how
to build features and it is very close to spoken languages.
Ruby is being used in wide range of fields, especially in Web Applications and data
science.
Ruby is a dynamic programming language therefore, it does not have hard rules on how
to build features and it is very close to spoken languages.
One of the goals of Ruby is to allow the simple and fast creation of Web applications.
Because of this there is much less tedious workthan many other programming
languages. Ruby provides small, elegant and powerful code.
Ruby is an open source language. It is free to copy, use, modify and distribute. Since
Ruby is available to be used in other projects, programmers can make necessary
changes and can code without feeling restricted.
Programmers are allowed to maintain reference counts in extension libraries with the
help of mark-and-sweep garbage collection, which is one of the features of Ruby. It can
also dynamically load extension libraries.
Difference between Ruby and Ruby on Rails:
Ruby is a programming language whereas Ruby on Rails is a Web framework.
Ruby is an Object Oriented, dynamic, interpreted scripting language whereas Ruby on
Rails is an Open source Web application framework, which runs on the Ruby
programming language.
Ruby on Rails:
Ruby on Rails (RoR) is an open source Web application frameworks.
Ruby on Rails is one of the main features of Ruby.
The programming language, Ruby is used to write Ruby on Rails.
Ruby on Rails, simply called Rails was designed for Ruby by David Heinemeier
Hansson.
It was released in July 2004.
Ruby versus Java:
Ruby based program runs directly as it is an interpreted scripting language whereas
Java- based codes are first compiled then executed.
Ruby does not have any data types as Java. In Ruby the constructor name is always
"initialize" whereas in case of Java the constructor name is the name of the class.
Ruby uses dynamic typing whereas Java uses static typing.
static typing vs dynamic typing
Dynamically- typed languages perform type checking at runtime, while statically
typed languages perform type checking at compile time.... If a script written in a
statically-typed language (such as Java) contains errors, it will fail to compile until the
errors have been fixed.
Popular Ruby Editors
To write your Ruby programs, you will need an editor –
If you are working on Windows machine, then you can use any simple text editor
like Notepad or Edit plus.
VIM (Vi IMproved) is a very simple text editor. This is available on almost all Unix
machines and now Windows as well. Otherwise, your can use your favourite vi editor
to write Ruby programs.
RubyWin is a Ruby Integrated Development Environment (IDE) for Windows.
Ruby Development Environment (RDE) is also a very good IDE for windows users.
Interactive Ruby (IRb)
Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you
can immediately view expression results, line by line.
This tool comes along with Ruby installation so you have nothing to do extra to have
IRb working.
Just type irb at your command prompt and an Interactive Ruby Session will start as
given below
$irb
irb 0.6.1(99/09/16)
irb(main):001:0> def hello
irb(main):002:1> out "Hello World"
irb(main):003:1> puts out
irb(main):004:1> end
nil
irb(main):005:0> hello
Hello World
nil
irb(main):006:0>
Ruby - Syntax
Let us write a simple program in ruby. All ruby files will have extension .rb. So, put the
following source code in a test.rb file.
puts "Hello, Ruby!";
Here, we assumed that you have Ruby interpreter available in /usr/bin directory. Now, try to
run this program as follows -
• $ ruby test.rb
• This will produce the following result -
Hello, Ruby!
Ruby Identifiers
Identifiers are names of variables, constants, and methods. Ruby identifiers are case
sensitive.
It means Ram and RAM are two different identifiers in Ruby.
A
a
Reserved Words
The following list shows the reserved words in Ruby. These reserved words may not be used
as constant or variable names. They can, however, be used as method names.
BEGIN And When
Do End Case
Next Or For
Then Unless Retry
END Begin While
Else Ensure Class
Nil reDO If
True Until Return
Alias Break Definse
Elsif False If_FILE_
Not Rescue Defined
Undef _LINE_ ?
Ensure Super Module
Ruby Is Object-Oriented
Ruby is a completely object-oriented language. Every value is an object, even simple
numeric literals and the values true, false, and nil (nil is a special value that indicates
the absence of value; it is Ruby's version of null). Here wevoke a method named class
on these values. Comments begin with #in Ruby, and the arrows in the comments
indicate the value returned by the commented code
1.class # Fixnum: the number 1 is a Fix num
0.0.class #=> Float: floating-point numbers have class Float
true.class #TrueClass: true is a the singleton instance of TrueClass
false.class#> FalseClass
nil.class #>NilClass
false.class #=> FalseClass
nil.class #=> NilClass
Blocks and Iterators
They are a special kind of method known as an iterator, and they behave like loops
The code within curly braces -known as a block-is associated with the method
invocation and serves as the body of the loop.
The use of iterators and blocks is another notable feature of Ruby; although the
language does support an ordinary while loop, it is more common to perform loops with
constructs that are actually method calls.
3. times { print "Ruby!" } # Prints "Ruby! Ruby! Ruby!"
1.upto(9) {|x| print x } # Prints "123456789"
Ruby Comments
A comment hides a line, part of a line, or several lines from the Ruby interpreter
You can use the hash character
(#) at the beginning of a line-
# I am a comment. Just ignore me.
Or, a comment may be on the same line after a statement or expression –
name = "Madisetti" # This is again comment
You can comment multiple lines as follows-
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Ruby vs Perl - Differences
Following are some of the basic differences of Ruby vs Perl:
1. Development and Release
1. Perl programming language was developed by Larry Wall and released in the year of
1987. Ruby is a newcomer in the programming industry. And it was developed and
released in 1995 by Yukihiro Matsumoto.
2. Web Frameworks
o In the matter of Ruby vs Perl, Catalyst is a major and most used Perl-based web
framework while Ruby on rails is a major web framework used for Ruby. Ruby on Rails
is an open-source web application framework. To write in this, Ruby programming
language is used.
3. Unicode Support
o When it comes to Unicode support, Perl language has much stronger support for
Unicode than Ruby language. For example, Perl supports all Unicode properties,
graphemes, and full case mapping.
o Ruby programming language do not support all these.
4. Object Orientation
o Ruby language is a pure object-oriented programing language. But Pearl, up to the 5th
version, is very less objective-oriented. But the upcoming version of Pearl is coming
with very good OO support.
o Objective-oriented programming stands for a physical model of programming
execution. It simulates the behavior of either a real or imaginary part of the world.
o The developer of Perl believes that choosing of OO should be the programmer's
decision; language should not force a programmer to switch to 00.
#class variables
@@type_of_animal = 4
@@no_of_animal = 3
end
Syntax:
• object_name = Class_name.new
# class name is box
class Box
# class variable
@@No_of_color = 3
end
# Two Objects of Box class
sbox Box.new
nbox Box.new
Defining Method in Ruby:
In Ruby member functions are called as methods.
• Every method is defined by the def keyword followed by a method name. The name of the
method is always in lowercase and the method ends with end keyword. In
Syntax:
def method_name
#statements or code to be executed
end
#Ruby program to illustrate
#defining class Vehicle
class GFG
#defining method def geeks
# printing result puts "Hello Geeks!"
#end of method end
#end of class GFG end
#creating object obj=GFG.new
Output:
Welcome to GeeksforGeeks!
Ruby BEGIN Statement
Syntax
BEGIN {
code
code2
}
Declares code to be called before the program is run.
Example
puts "This is main Ruby Program"
BEGIN
{
puts "Initializing Ruby Program"
}
Local variables
Instance variables
Class variables
Global variables
Each variable in Ruby is declared by using a special character at the start of the variable name
which is mentioned in the following table:
• Symbol Type of Variable
• [a-z] or_ Local Variable
•@ Instance Variable
• @@ Class Variable
$ Global Variable
• Local Variables: A local variable name always starts with a lowercase letter(a-z) or
underscore (_). These variables are local to the code construct in which they are declared. A
local variable is only accessible within the block of its initialization. Local variables are not
available outside the method. There is no need to initialize the local variables.
Example:
⚫ age = 10
• _Age = 20
• Instance Variables: An instance variable name always starts with a @ sign. They are similar
to Class variables but their values are local to specific instances of an object. Instance variables
are available across methods for any specified instance or object i.e. instance variables can
change from object to object. There is no need to initialize the instance variables and
uninitialized instance variable always contains a nil value.
class Customer
#displaying result
def display details() puts "Customer id #@cust_id"
puts "Customer name #@cust name"
puts "Customer address @cust addr"
end
end
#Create Objects
cust1 Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 Customer.new("2", "Poul", "New Empire road, Khandala")
Output:
Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya
Customer id 2 Customer name Poul Customer address New Empire road, Khandala
#Call Methods
Cust1.display_details ()
Cust2.display_details ()
Cust1.display details () cust2.display details ()
Class Variables: A class variable name always starts with @@ sign.lt is available across
different objects. A class variable belongs to the class and it is a characteristic of a class.
They need to be initialized before use. Another way of thinking about class variables is as
global variables within the context of a single class. A class variable is shared by all the
descendants of the class. An uninitialized class variable will result in an error.
2. The Structure and Execution of Ruby Programs
⚫ files, explaining how Ruby programs can be split across multiple files and how the Ruby
interpreter executes a file of Ruby code
Ruby lexical structure
• Computer languages, like human languages, have a lexical structure.
• A source code of a Ruby program consists of tokens. Tokens are atomic code elements.
• In Ruby language we have various lexical structures, such as comments, variables, literals,
white space, operators, delimiters, and keywords.
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 are used by humans to clarify the source code. There are two types of
comments in Ruby. Single- line and multi-line comments. Single-line comments begin
with the #character. Multi-line comments are put between the begin and end tokens.
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 (but does not
ignore the newline character, which is meaningful whitespace and may serve as a
statement terminator).
#This entire line is a comment
• Multiline comments are usually written simply by beginning each line with a separate
# character:
#
# This class represents a Complex number
# Despite its name, it is not complex at all.
#
Note that Ruby has no equivalent of the C-style /*...*/ comment.
• =begin
comments.rb
author Jan Bodnar
=end
# prints message to the terminal puts "Comments example"
Embedded documents
O/P:
8
5
8
Punctuation
• Most Ruby operators are written using punctuation characters, such as + for addition, * for
multiplication, and || for the Boolean OR operation.
2.4 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 and they may not include punctuation characters
except as described here
A variable is an identifier, which holds a value. In programming we say that we assign
a value to a variable. Technically speaking, a variable is a reference to a computer
memory, where the value is stored. In Ruby, a variable can hold a string, a number or
various objects. Variables can be assigned different values over time.
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:
i
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
Value
value2
company_name
These are valid variable names.
12Val
exx$
first-name
These are examples of invalid variable names.
• 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 untile
Alias else module return when
And elsif next self while
Begin end nil super yield
Ruby delimiters
A delimiter is a sequence of one or more characters used to specify the boundary
between separate, independent regions in plain text or other data stream
() [] {} , ; '" ||
name = "Jane"
occupation = 'Student'
numbers = [2, 3, 5, 3, 6, 2]
puts name;
puts occupation
puts numbers[2]
numbers.each { |i| puts i } puts (2+3)*5
Ruby operators
An operator is a symbol used to perform an action on some value.
(answers.com)
!
+
-
~
*
**
/
%
<< >>
& ^== === != < = > >
<= ... not and or ?:
&& ||
Ruby blocks
Ruby statements are often organized into blocks of code. A code block can be delimited
using {} characters or do and end keywords.
Flow control of Ruby code is often done with the if keyword. The keyword is followed
by a block of code. In this case a block of code is delimited by then, end keywords,
where the first keyword is optional.
if true then
puts "Ruby language"
puts "Ruby script"
end
In the above example, we have a simple block of code. It has two statements. The block is
delimited by then, end keywords. The then keyword can be omitted
Ruby constants
Constants are value holders which hold only one value over time. An identifier with a
first uppercase letter is a constant in Ruby. In programming it is a convention to write
all characters of a constant in uppercase.
Unlike in other languages, Ruby does not enforce constants to have only one value over
time. The interpreter only issues a warning if we assign a new value to an existing
constant.
Name = "Robert"
o AGE = 23
o Name = "Juliet"
In the above example, we create two constants. One of the constants is redefined later.
We redefine a constant. Which issues a warning.
Syntactic Structure
Now we move on to briefly describe how those lexical tokens combine into the larger
syntactic structures of a Ruby program
This section describes the syntax of Ruby programs, from the simplest expressions to
the largest modules
Operators are used to perform computations on values, and compound expressions are
built by combining simpler subexpressions with operators:
1 # A primary expression
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
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
Block Structure in Ruby
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!" }
File Structure
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
10 stream object DATA
#!/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
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
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.
Actually, that last statement is not quite true.
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.
Ex:
x=1
if x>2
puts "x is greater than 2"
elsif x<=2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
Ruby while Statement
• Loops in Ruby are used to execute the same block of code a specified number of times. This
chapter details all the loop statements supported by Ruby.
while conditional [do]
code
end
Ex:
Si=0
$num=5
while $i <$num do
puts("Inside the loop i = #$i" )
$i +=1
End
Ruby Gems
RubyGems is a package utility for Ruby, which installs Ruby software packages and
keeps them up-to-date.
Check to see whether RubyGems is installed -
$ gem --version
0.9.0
How do RubyGems work?
• The RubyGems software allows you to easily download, install, and use ruby software
packages on your system .... Gems can be used to extend or modify functionality in
• In the RubyGems world, developers bundle their applications and libraries into single
files
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.
The gem command allows you to interact with RubyGems.
FINDING GEMS
The search command lets you find remote gems by name. You can use regular expression
characters in your query:
• If you see a gem you want more information on you can add the details option.
$gem search rails -d
REMOTE GEMS***
Rails (7.0.3)
Author: David Meinemeier Hansson
Homepage: https://rubyonrails.org
Full-stack web application framework.
INSTALLING GEMS
The install command downloads and installs the gem and any necessary dependencies
then builds documentation for the installed gems.
STRUCTURE OF A GEM
o each gem has a name, version, and platform. For example, the rake gem has a
0.8.7 version (from May, 2009). Rake's platform is ruby, which means it works
on any platform Ruby runs on.
o Platforms are based on the CPU architecture, operating system type and
sometimes the operating system version. Examples include "x86-mingw32" or
"java". The platform indicates the gem only works with a ruby built for the same
platform.
o RubyGems will automatically download the correct version for your platform.
See gem help platform for full details.
o Inside gems are the following components:
o Code (including tests and supporting utilities)
o Documentation
gemspec
THE GEMSPEC
The gemspec specifies the information about a gem such as its name, version, description,
authors and homepage.
Gem::Specification.new do |s|
s.name = 'example'
s.version = '0.1.0'
s.licenses = ['MIT']
s.summary = "This is an example!"
s.description = "Much longer explanation of the example!"
s.authors = ["Ruby Coder"]
s.email = '[email protected]'
s.files = ["lib/example.rb"]
s.homepage = 'https://rubygems.org/gems/example'
s.metadata = { "source_code_uri" =>
"https://github.com/example/example" }
end
$ tree
.
├── Rakefile
├── bin
│ └── hola
├── hola.gemspec
├── lib
│ ├── hola
│ │ └── translator.rb
│ └── hola.rb
└── test
└── test_hola.rb
• To use RubyGems, you'll first need to download and install the RubyGems system
from the project's home page at http://rubygems.rubyforge.org
• % cd rubygems0.7.0
• % ruby install.rb
• The best way to test that RubyGems was installed successfully also happens to be the
learn
• % gem help
Installing Application Gems
• Let's start by using RubyGems to install an application that is written in Ruby. Jim
Weirich's Rake (http://rake.rubyforge.org) holds the distinction of being the first
application that was available as a gem.
• % gem install -r rake
• % rake --version
• # gem install rails
Successfully installed activesupport-1.4.4
Successfully installed activerecord-1.15.5
Successfully installed actionpack-1.13.5
Successfully installed actionmailer-1.3.5
Successfully installed actionwebservice-1.2.5
Successfully installed rails-1.2.5
6 gems installed
As you can see, the gem install command installs the most recent version of the gem
you request and also installs any gems that the requested gem requires
2, Web server receives the request message will be parsed URL and look accessed files
on the server if there is to return the contents of the file, otherwise it returns an error
message.
3, the browser …messages.
CGI programs can be a Ruby script, Python script, PERL script, SHELL script, C or C
++ programs.
CGI Chart
WEB SERVER
WEB CLIENT
SERVER SIDE SCRIPT
DATABASE
HTTP Protocol
• Web server configuration and support before you conduct CGI programming, make sure that
your Web server has been configured to support CGI and CGI handler.
• Apache supports CGI configuration:
• What is Common Gateway Interface (CGI)?
CGI is not a language. It's a simple protocol that can be used to communicate between
Web forms and your program.
• A CGI script can be written in any language that can read STDIN, write to
STDOUT, and read environment variables, i.e. virtually any programming
language, including C, Perl, or even shell scripting.
<space> => +
To handle the above characters, cgi provides you .escape and .unescape. They are
routines of cgi. See the
example given below for reference:
require 'cgi'
puts CGI.escape( "He/She must be aware of his/her capabilities & should work accordingly")
Output
He%2FShe+must+be+aware+of+his%2Fher+capabilities+%26+should+ work+accordingly
⚫ he following code will let you know how you can escape HTML special characters?
• puts CGI.escapeHTML( '<a href="/san">Go to the site (Includehelp.com)</a>')
• Output
<a href="/san">Go to the site(Includehelp.com)</a>
cgi class is an umbrella of the huge number of methods which are necessary to write
HTML. Every tag has got a method under cgi. cgi is a class and we all that to access
the methods of a class, first we have to instantiate it. cgi can be instantiated by calling
CGI.new.
Let us design a basic form with the help of code mentioned below,require "cgi
Require “cgi”
cgi = CGI.new("html5")
cgi.out {
cgi.html {
cgi.head { "\n"+cgi.title("It is an Example of forn" }} +
cgi.body { "\n" cgi.fora ("\n"+
cgi.from { "\n"+
cgi.hr +
cgi.hr1 { “A Form: “ } + "\n"+
cgi.hr2 { “A Basic form: “ } + "\n"+
cgi.text area("get_text") +"\n" +
cgi.button("click_here")+ " cgi.hr1 { “A Form: “ } + "\n"+
cgi.hr +
cgi.br +
cgi-submit
}
}
}
}
output
Content-Type: text/html
Content-Length: 317
<!DOCTYPE HTML><HTML><HEAD>
<TITLE>It is an Example of form</TITLE> </HEAD> <BODY>
<FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">
<HR><H1>A Form: </H1>
<H2>A Basic Form:</H2>
<TEXTAREA NAME="get text" COLS="70" ROWS="10"></TEXTAREA>
<BUTTON></BUTTON>
<HR><BR><INPUT TYPE="submit"></FORM></BODY></HTML>
The above code is producing an HTML form having title "This is an example". The form has
horizontal rulers, Headings, two Input controls namely TextArea and button. All the code
blocks will return a string which will be utilized as the content for the tag.
Cookies
Cookies are a way of letting Web applications store their state on the user's machine.
Cookies are still a convenient (if unreliable) way of remembering session information.
The Ruby CGI class handles the loading and saving of cookies for you.
You can access the cookies associated with the current request using the CGI#cookies
method, and youcan set cookies back into the browser by setting the cookies parameter
of CGI#out treference either a single cookie or an array of cookies
reference either a single cookie or an array of cookies.
#!/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 }
Ruby/Tk Introduction
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 eabl
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 Active
Tcl.
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
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
any parameters provided by the program when it asks the geometry manager to manage
that particular slave widget.
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.
grid Geometry manager that arranges widgets in a grid.
grid Geometry manager that arranges widgets in a grid
pack Geometry manager that packs around edges of cavity.
place Geometry manager for fixed or rubber-sheet placement.
• Syntax
To specify an absolute position, use the x and y options. To specify a position relative
to the parent window or the widget, use the relx and rely options.
In addition, you can specify the relative size of the widget by using the relwidth and
relheight options provided by this geometry manager.
• Syntax
Here is a simple syntax to create a place Widget -
⚫ place(relx'=>x, 'rely'=>y)
Examples
Following is the code which implements the place geometry manager-
require 'tk
top=TkRoot.new (title "Label and Entry Widget"]
#code to add a label widget
Ib1TkLabel.new(top){
text "Hello World"
background "yellow" foreground "blue"
place('relx'>0.0, 'rely'>0.0)
#code to add a entry widget
e1 = TkEntry.new(top) background "red" foreground "blue" place('relx>0.4,'rely'>0.0)
Tk.mainloop
• A Canvas widget implements structured graphics. A canvas displays any number of items,
which may be things like rectangles, circles, lines, and text.
• Syntax
TkCanvas.new {
.....Standard Options.....
.....Widget-specific Options....
}
......Widget-specific Options....
}
Creating Item
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
Arc Items
Bitmap Items
Image Items
Line Items
Rectangle Item
• 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
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.
Star> 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.
Tag =>staglist-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.
Image Items
Items of type image are used to display images on a canvas. Images are created with methods
of the following form::
• The Tkclmage.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.
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
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.
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.
• Example 1
• require "tk"
• canvas = TkCanvas.new
• TkcRectangle.new(canvas, '1c', '2', '3c', '3c', 'outline' => 'black', 'fill' => 'blue')
TkcLine.new(canvas, 0, 0, 100, 100, 'width' => '2', 'fill' => 'red')
• canvas.pack
• Ruby/Tk-Scrollbar Widget
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....
}
• require "tk"
• canvas = TkCanvas.new
• TkcRectangle.new(canvas, '1c', '2c', '3c', '3c', 'outline' => 'black', 'fill' => 'blue')
• Tk.mainloop
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.
• S method is used to query and change the vertical position of the text in the widget's window.