0% found this document useful (0 votes)
5 views43 pages

SL Notes Unit-1

The document provides an overview of programming and scripting languages, defining key concepts such as programs, scripts, and their execution. It introduces Ruby as a dynamic, open-source programming language with features like object-orientation and flexibility, along with its history and basic syntax. Additionally, it covers Ruby's structure, including comments, literals, identifiers, keywords, and the RubyGems package management system.
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)
5 views43 pages

SL Notes Unit-1

The document provides an overview of programming and scripting languages, defining key concepts such as programs, scripts, and their execution. It introduces Ruby as a dynamic, open-source programming language with features like object-orientation and flexibility, along with its history and basic syntax. Additionally, it covers Ruby's structure, including comments, literals, identifiers, keywords, and the RubyGems package management system.
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/ 43

UNIT - 1

Program:
Definition: A complete set of instructions that can be executed independently by a
computer to perform a specific task.
Script:
A set of instructions written in a scripting language designed to automate tasks within
another program is called a script.
Example:
Imagine you want to calculate the area of a rectangle.
Program: You could write a complete C++ program that takes the length and width as
input, performs the calculation, and displays the result. This program would be
compiled and run independently.
Script: You could write a Python script that uses a Python library to perform the
calculation. This script would be executed within a Python interpreter or embedded in
another program to calculate the area dynamically.

Programming Languages:

Definition: Programming languages are used to create standalone software


applications or systems. They involve writing code that is compiled or interpreted to
produce executable programs.
Key Points:
❖ Used for creating standalone software applications.
❖ Code is compiled or interpreted to produce executable programs.
Examples include C, C++, Java, and Swift.
Scripting Languages:
Definition: Scripting languages are used to automate tasks within other software
environments. They involve writing scripts that are interpreted and executed line by line
at runtime.
Key Points:
❖ Used for automating tasks within other software environments.
❖ Scripts are interpreted and executed line by line at runtime.
❖ Often used for tasks such as automation, web development, and system
administration.
❖ Examples include Perl, Ruby, TCL, JavaScript (for client-side scripting), and Bash
(for shell scripting).
Ruby Introduction

What is Ruby
Ruby is a dynamic, open source, object oriented and reflective programming language.
Ruby is considered similar to Perl and Smalltalk programming languages. It runs on all
types of platforms like Windows, Mac OS and all versions of UNIX.
Dynamic: In programming languages, "dynamic" typically refers to a language's ability
to execute code and make decisions at runtime, as opposed to compile time. Dynamic
languages allow for flexibility and adaptability during program execution. This can
include dynamic typing (where variables are not assigned a fixed type and can change
during execution), dynamic method invocation (where methods can be called based on
runtime conditions), and dynamic code generation (where new code can be created
and executed during runtime).
Reflective: Reflective programming, on the other hand, refers to a language's ability to
examine and modify its own structure and behavior at runtime. This means that the
program can introspect itself, analyze its own code, and modify its behavior or
structure dynamically while it is running. Reflective languages provide features such as
introspection (examining the properties of objects, classes, or methods at runtime),
intercession (modifying the behavior of objects, classes, or methods at runtime), and
meta-programming (writing code that generates or modifies other code dynamically).
History of ruby:
Ruby was designed and developed by Yukihiro "Martz" Matsumoto in mid 1990s in
Japan.
Why the name Ruby:
The name "Ruby" originated during a chat session between Matsumoto and Keiju
Ishitsuka. Two names were selected, "Coral" and "Ruby". Matsumoto chose the later
one as it was the birthstone of one of his colleagues.
Features of ruby:
❖ Object-oriented
❖ Flexibility
❖ Expressive feature
❖ Mixins
❖ Visual appearance
❖ Dynamic typing and Duck typing
❖ Exception handling
❖ Garbage collector
❖ Portable
❖ Keywords
❖ Statement delimiters
❖ Variable constants
❖ Naming conventions
❖ Keyword arguments
❖ Method names
❖ Singleton methods
❖ Missing method
❖ Case Sensitive
Hello World Program Execution in different languages:

Java Ruby

class HelloWorld puts "Hello World"

public static void main(String argos[])

System.out.println("Hello World");

Java Execution: Ruby Execution:


javac file_name.java ruby file_name.rb
java file_name

The structure and Execution of Ruby Programs:


1. Lexical Structure
2. Syntactic Structure
3. File Structure
4. Program Encoding
5. Program Execution

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:
Statements that are not executed by the interpreter are called Comments.They are
written by a programmer to explain their code so that others who look at the code will
understand it in a better way.
Types of Ruby comments:
1. Single line comment
2. Multi line comment
Single line comment:
The Ruby single line comment is used to comment only one line at a time. They are
defined with # character.
Example:
#This is a single line comment.
i = 10 #Here i is a variable.
puts i
Multiline comment:
The Ruby multi line comment is used to comment multiple lines at a time. They are
defined with =begin at the starting and =end at the end of the line.
=begin
This
is
multi line
comment
=end
*Multiline comment is also known as an embedded document.
Documentation comments (rDoc and ri):
rDoc stands for Ruby Documentation
rDoc is a tool used in Ruby for generating documentation for Ruby code. It allows
developers to document their code in a structured manner using comments, and then
automatically generates HTML or other formats of documentation from those
comments.
ri stands for Ruby Interactive. It's a command-line tool that comes bundled with Ruby. ri
allows you to access documentation for Ruby classes, modules, and methods directly
from the command line.
Example for ri:

**To get this , ruby must be installed


Literals:
A literal is any value we specify as a constant in the code.They include numbers,
strings of text, and regular expressions etc.
Example:
1 # An integer literal
1.0 # A floating-point literal
'One' # A string literal
"Two" # Another string literal
/three/ # A regular expression literal
Punctuation:
Ruby uses punctuation characters for a number of purposes. Most Ruby operators are
written using punctuation characters, such as + for addition, * for multiplication, and ||
for the Boolean OR operation.Punctuation characters also serve to delimit string,
regular expression, array, and hash literals, and to group and separate expressions,
method arguments, and array indexes.
Identifiers:
An identifier is simply a name. Ruby uses identifiers to name variables, methods,
classes etc
● Ruby identifiers consist of letters, numbers, and underscore characters (_).
● Identifiers may not begin with a number.
● Identifiers may begin with _ symbol..
● Identifiers may not include whitespace or nonprinting characters.
● Class and module names must begin with an initial capital letter according to
Ruby convention.
Example:
i
x2
old_value
_internal # Identifiers may begin with underscores
PI # Constant

❖ Ruby is a case-sensitive language. Lowercase letters and uppercase letters are


distinct. The keyword end, for example, is completely different from the keyword
END.
❖ Punctuation characters may appear at the start and end of Ruby identifiers.
Example:
$ 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.
Keywords / Reserved words:
There are certain words that are reserved for doing specific tasks. These words are
known as keywords and they have standard, predefined meaning in Ruby.
Some of the keywords available in Ruby are given below:

BEGIN END alias and begin break case


class def module next nil not
or
redo rescue retry return elsif end false
Ensure for if true undef unless do
else super then until when while etc….
These keywords cannot be used for naming variables or constants in Ruby.

Whitespaces:
In Ruby, whitespace refers to any sequence of spaces, tabs, and newline characters in
the code that serve to separate tokens.
Ruby statements are typically terminated by a newline character, indicating the end of a
line of code
Never put a space between a method name and the opening parenthesis.
Syntactic structure
The expression is the most basic unit of syntax in Ruby. The Ruby interpreter is a
programme that evaluates expressions and returns values. Primary expressions, which
represent values directly, are the simplest. Primary expressions include number and
string literals, which were discussed earlier in this chapter. Some keywords, such as
true, false, nil, and self, are also main expressions. Variable references are primary
expressions as well; they evaluate the variable's value.
Compound expressions can be used to express more complex values:
[1,2,3] #An Array literal
{1=>"one", 2=>"two"} #A Hash literal
1..3 #A Range literal
To execute computations on values, operators are utilised, and compound expressions
are created 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)
Statements like the if statement for conditionally executing code and the while
statement for continually executing code can be created by combining expressions
with Ruby's keywords:
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
Block structure:
Ruby programs have a block structure.
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.
To avoid ambiguity with these true blocks, we can call the other kind of block a body
A body is just the list of statements that comprise the body of a class definition, a
method definition, a while loop, or whatever.
Bodies and blocks can be nested within each other, and Ruby programs typically have
several levels of nested code, made readable by their relative indentation. Here is a
schematic example:
module Stats # A module
class Dataset # A class in the module
def initialize(filename) # A method in the class
IO.foreach(filename) do |line| # A block in the method
if line[0,1] == "#" # An if statement in the block
next # A simple statement in the if
end # End the if body
end # End the block
end # End the method body
end # End the class body
end # End the module body
File Structure:
There are only a few rules about how a file of Ruby code must be structured.
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.
#!/usr/bin/ruby
Using __END__:
❖ If a file contains the line __END__ without any whitespace before or after it, the
Ruby interpreter stops processing the file at that point. The rest of the file can
contain arbitrary data that the program can read using the IO stream object
DATA.
Example:
#!/usr/bin/env ruby
# This script calculates the sum of numbers from 1 to 10.
sum = 0
(1..4).each do |n|
sum += n
end
puts "The sum of numbers from 1 to 4 is: #{sum}"
__END__
This is the end of the Ruby script.
To read DATA lines
DATA.each_line do |line|
puts line
end
Program encoding:
❖ Character encoding is a way to represent characters as numbers in binary
format.
❖ Different encoding schemes exist, such as ASCII, UTF-8, UTF-16, ISO-8859-1
(Latin-1), etc.
❖ Each encoding scheme assigns a unique binary code to each character in its
character set.
➢ By default, Ruby assumes that source code is encoded in ASCII, but it can
process files with other encodings as long as they can represent the full
set of ASCII characters.ASCII value for some of the characters are.
➢ #(hash)-35,newline-10,space-10
➢ In Ruby 1.8, you can specify a different encoding with the -K command-
line option. To run a Ruby program that includes Unicode characters
encoded in UTF-8, invoke the interpreter with the -Ku option.
➢ From ruby 1.9 version ,the encoding can be specified using special
comments like # coding: utf-8.
➢ Encoding names are not case-sensitive,ASCII-8BIT,US-ASCII (7-bit
ASCII),ISO-8859-1,the Japanese encoding SHIFT_JIS (also known as SJIS)
and EUC-JP are encoding types.
➢ The encoding comment must be entirely in ASCII and must include the
string "coding" followed by a colon or equals sign and the name of the
desired encoding.

Setting Program Encoding:


❖ In Ruby 1.9 and later versions, the preferred way to specify the encoding of a
program file is by placing a special "coding comment" at the start of the file.
❖ There are different options for setting the encoding via command-line options (-
K, -E, --encoding).
❖ Default External Encoding:
➢ Ruby also has a default external encoding, which affects how Ruby reads
from files and streams.
➢ The default external encoding is typically set based on the system's
locale settings.
➢ You can query and set the default external encoding using methods like
Encoding.default_external.

Program Execution:
In Ruby, programs are scripts consisting of statements executed sequentially by
default. There is no special main method like in statically compiled languages. The
Ruby interpreter executes scripts from the first line to the last line, with some
exceptions:
BEGIN and END Statements: Before executing the main body of the script, the
interpreter scans for BEGIN statements and executes their code. Similarly, after
executing the main body, it executes any END statements or registered "shutdown
hook" code using the at_exit function.
Module, Class, and Method Definitions: Unlike in compiled languages where these are
syntactic structures processed by the compiler, in Ruby, they are executable
statements. When encountered, the interpreter executes them, causing the respective
modules, classes, and methods to be defined.
Program Invocation: The Ruby interpreter is invoked from the command line, where it
reads and executes the specified script file. It continues executing until encountering:
● A statement that causes the program to terminate.
● The end of the file.
● A line with the token __END__, marking the logical end of the file.
Package Management with RUBYGEMS:

Gems:
In the RubyGems world, developers bundle their applications and libraries into single
files called gems.
RubyGems:
RubyGems is a standardized packaging and installation framework for libraries and
applications, making it easy to locate, install, upgrade, and uninstall Ruby packages.
or
RubyGems is a big library where you can find and get these packages (gems). It helps
to find, install, and manage the gems in Ruby projects.
RubyGems system provides a command-line tool, appropriately named gem, for
manipulating these gem files.

Installing RubyGems

when you install Ruby, RubyGems will be automatically installed along with it. This is
because RubyGems is the standard package manager for Ruby, and it's essential for
managing libraries and dependencies in Ruby projects.
To check whether RubyGem was installed or not ,use the following command in
command prompt

e:\ gem help


Installing Application Gems:

Rake:Rake is used to automate tasks in the development process, such as compiling


code, running tests, deploying applications, and more. Rake uses Ruby's language
syntax to define tasks and dependencies

Rake typically comes pre-installed with Ruby, so you usually don't need to install it
separately. However, if you need to install a specific version or want to ensure you have
the latest version, you can install it using RubyGems, the package manager for Ruby:

% gem install -r rake


Attempting remote installation of 'Rake'
Successfully installed rake, version 0.4.3
% rake --version
rake, version 0.4.3

❖ -r means remotely
If for some reason—perhaps because of a potential compatibility issue—you wanted
an older version of Rake, you could use RubyGems’ version requirement operators to
specify criteria by which a version would be selected.

% gem install -r rake -v "< 0.4.3"


Attempting remote installation of 'rake'
Successfully installed rake, version 0.4.2
% rake --version
rake, version 0.4.2

Operator Description
= Exact version
!= Any version that is not one mentioned
> Any version that is greater than the one
specified
< Any version that is less than the one specified
>= Any version that is greater than or equal to
specified <= Any version that is less
than or equal to specified
~> Boxed version operator. Version must be
greater than or equal to the specified version
and less than specified version after having its
minor version number increased by one.
Creation of Rakefile and execution:
create a simple Rakefile that defines tasks to greet users in different languages:

To save the Rakefile program, you can follow these steps:

❖ Open a text editor or an Integrated Development Environment (IDE) of your


choice.
❖ Copy the provided Rakefile code into a new file.
❖ Save the file with the name Rakefile (note the capital "R" and No file extension).

Write the below code in any editor (Notepad)


# Define a task to greet users in English
task :english do
puts "Hello, World!"
end
# Define a task to greet users in French
task :french do
puts "Bonjour tout le monde !"
end
# Define a task to greet users in Spanish
task :spanish do
puts "¡Hola, mundo!"
end
After writing the above code save the file with Rakefile(R should be capital and no
extension for program)
In this example:
● We've defined three tasks: :english, :french, and :spanish, each using the task
method.
● Each task simply prints a greeting message in the respective language.
To run these tasks, you use the rake command followed by the task name:
rake english # To greet users in English
rake french # To greet users in French
rake spanish
Installing and Using Gem Libraries:
Installing predefined gems means adding already-made tools and features to your
Ruby projects using RubyGems. These gems include various helpful libraries and
utilities that make your Ruby coding easier and more powerful. With RubyGems, you
can quickly access a diverse range of components designed to speed up your
development process, simplify tasks, and expand what your applications can do.
Whether you need to work with JSON data, handle CSV files, connect to databases, or
interact with external services, predefined gems provide an easy way to add these
capabilities to your projects. All it takes is a few simple commands to install, manage,
and use these gems, boosting your Ruby development experience.
❖ To see available predefined gems the command used is (Execute commands in
cmd)
gem list
❖ To install gem the command used is
gem install gem_name
❖ To see the documentation of the libraries, the command used are
ri and rdoc
Example:
One commonly used predefined gem in Ruby is the csv gem, which provides
functionality for working with comma-separated values (CSV) files.
This simple example demonstrates how to use the csv gem to read data from a CSV
file in Ruby. The csv gem provides convenient methods for working with CSV files,
making it easy to parse and manipulate CSV data in your Ruby applications.
Step 1: install csv gem using following command
c:\Users\kits> gem install csv

Step 2: After successfully installing the csv gem , now we have to use this in our
program.
Create a excel file in any directory and type the data like

Save the above with .csv extension.


Next, Create a notepad file and type the following code (csv and this notepad should
be in the same directory)
require 'csv'
# Define the path to the CSV file
csv_file = 'example.csv'
# Read data from the CSV file and print it
CSV.foreach(csv_file) do |row|
puts row.join(', ')
end
Save this file with test.rb
Next execute the ruby file in command prompt
Creating Your Own Gems:
Setup Environment: Ensure you have Ruby installed on your system. You can check the
installation by running ruby -v in your terminal. Also, ensure you have RubyGems
installed (gem -v). If not, install it. If ruby is installed then automatically Rubygems is
also installed.
1. Package Layout:
The package layout refers to how your gem's files and directories are organized. In the
case of factorial gem, we have a directory structure with lib for the main code, test for
testing files, and additional files like README.md and factorial.gemspec for metadata
and documentation.
You can use the bundle gem command to create a new gem. Open your terminal and navigate
to the directory where you want to create your gem.
For Example: In E: (in any directory) drive create a folder, Example ruby(name can be anything)
After creating folder move to that folder
E:/>cd ruby
E:/>ruby
Now execute the command bundle gem factorial
E:\ruby>bundle gem factorial
This will create a directory named factorial with the basic structure for a gem.
Now in E:\ruby a folder is created

2. The Gem Specification:


The gem specification (factorial.gemspec) is a crucial file that defines the metadata
for your gem. This includes details such as the gem's name, version, description,
author information, and files to include in the gem. It's essentially the blueprint for your
gem's construction.
❖ factorial.gemspec file present in e:/ruby/factorial folder, Write the following
code in factorial.gemspec file.
# frozen_string_literal: true
require_relative "lib/factorial/version"
Gem::Specification.new do |spec|
spec.name = "factorial"
spec.version = "0.0.0"
spec.authors = "Dev"
spec.email = "[email protected]"
spec.summary = "Factorial program"
spec.description = "this program is for factorial"
spec.files = ["lib/factorial.rb"]
spec.homepage ="https://rubygems.org/gems/factorial"
spec.license = "MIT"
spec.required_ruby_version = ">= 2.6.0"
end
❖ After writing the above code, save the file and close.
3. Runtime Magic:
In the lib/factorial.rb file, we define the actual functionality of our gem. Here, we
implement the calculate method of the Factorial module, which computes the
factorial of a given number. This is where the core logic of your gem resides,
and it's what users will interact with when they use your gem.
❖ Inside the lib/factorial.rb file, we have to define the functionality of the gem.
open factorial.rb file and remove all content and type the following code

# frozen_string_literal: true
require "factorial"
module Factorial
def self.calculate(n)
if n == 0 || n == 1
1
else
n * calculate(n - 1)
end
end
end
Then save the file and close the file
4. Adding Tests and Documentation:
Tests and documentation are essential components of any well-maintained gem. In
test/factorial_test.rb, we write tests to ensure that our calculate method behaves as expected
under different scenarios. Documentation comments in lib/factorial.rb help users understand
how to use the gem and what each method does.
❖ Create a folder test in e:/ruby/factorial.
❖ Create a notepad file(factorial_test.rb) and type the following code
require 'test/unit'
require '../lib/factorial'
class TestFactorial < Test::Unit::TestCase
def test_factorial
assert_equal(1, Factorial.calculate(0))
assert_equal(1, Factorial.calculate(1))
assert_equal(120, Factorial.calculate(5))
assert_equal(3628800, Factorial.calculate(10))
end
end

5. Adding Dependencies:
If your gem relies on other gems or libraries, you specify those dependencies in the gemspec.
For example, if our factorial gem required the bigdecimal gem for handling large numbers, we
would add it as a dependency in the gemspec. This ensures that users can easily install and
use your gem along with its dependencies.
To add a dependency on the bigdecimal gem in your gemspec file, you would include it like
this:
❖ spec.add_dependency 'bigdecimal'
This line tells RubyGems that your gem depends on the bigdecimal gem. When users
install your gem, RubyGems will automatically ensure that the bigdecimal gem is also
installed if it's not already.
6. Ruby Extension Gems:
In some cases, your gem might include C extensions or native code for performance
reasons or to interface with external libraries. You'd need to handle these extensions
properly and specify them in the gemspec to ensure that they're compiled and included
correctly when users install your gem.
7. Building the Gem File:
Once you've defined your gemspec and organized your files, you can use the gem build
command to generate a gem file (.gem). This file contains all the necessary files and
metadata required to distribute your gem.
Open cmd(E:\ruby/factorial) and type the following command
gem build factorial.gemspec

Install Gem Locally: You can install the gem locally to test it in your system.

Now we have to use factorial gem


Create a notepad in E:/ruby/factorial and the following code
require "factorial"
puts Factorial.calculate(5)
Save the notepad with .rb extension
Next open cmd and execute the file

8. Maintaining Your Gem:


Maintaining your gem involves ongoing tasks such as fixing bugs, adding features, updating
documentation, and ensuring compatibility with new versions of Ruby and its dependencies. It
also involves responding to user feedback, addressing issues, and keeping your gem's
ecosystem healthy and up-to-date.

RUBY AND THE WEB


Writing CGI Scripts:
What are CGI scripts:
CGI, or Common Gateway Interface, is a protocol for web servers to interact with
external programs. Ruby provides a built-in library called CGI that makes writing CGI
scripts relatively easy. These scripts:
1. Run on the web server and are triggered by user requests (like clicking a button
or submitting a form).
2. Access information from the request (like form data, cookies, headers).
3. Generate dynamic content (like HTML pages) to be sent back to the user.
Uses:
1. CGI scripts were used to build small-scale web applications.
2. Scripts could handle form submissions, validate data, and generate responses.
3. They could add dynamic elements to static websites without a full framework.
Different types of CGI scripts:
Form Processing Scripts:
These scripts handle data submitted through HTML forms on web pages. They
extract form data from the HTTP request, process it (e.g., validate input, perform
calculations), and generate a response (e.g., confirmation message, updated
page).
Database Interaction Scripts:
CGI scripts can interact with databases to perform tasks such as retrieving data,
updating records, or executing queries. They receive input parameters from
users or other sources, process them, interact with the database using SQL
queries and return results as HTML or other formats.
File Upload and Management Scripts:
These scripts manage file uploads from users to the web server. They receive
files submitted via HTML forms, validate them (e.g., check file types, size limits),
and store them on the server filesystem. Additionally, they may handle file
retrieval, deletion, or other management tasks.
User Authentication and Authorization Scripts:
CGI scripts can authenticate users and enforce access control policies on web
applications. They verify user credentials (e.g., username/password) against a
database or other authentication source, set session tokens or cookies for
authenticated users, and enforce authorization rules to restrict access to certain
resources or actions.
Dynamic Content Generation Scripts:
These scripts dynamically generate web content based on various factors such
as user input, database queries, system status, or external data sources. They
construct HTML pages, generate charts or graphs, or customize content based
on user preferences or behavior.
Email Handling Scripts:
CGI scripts can send and receive emails as part of web applications. They
process email messages received from users or external systems, send email
notifications or confirmations, and handle email-related tasks such as
formatting messages, adding attachments, or parsing incoming emails for
specific content.
Execution of CGI scripts:
Install XAMPP:
Download and install XAMPP from the official website: XAMPP.
Follow the installation wizard and install it in the desired directory (e.g.,
C:\xampp).
4. Start Apache Server:
Launch the XAMPP Control Panel.
Start the Apache server by clicking on the "Start" button next to Apache.
5. Install Ruby:
Download RubyInstaller from RubyInstaller for Windows.
Run the installer and follow the installation instructions. Make sure to check the
option to add Ruby executables to your PATH during installation.
6. Configure Apache for CGI:
Open the XAMPP Control Panel.
Click on the "Config" button for Apache, then select "httpd.conf" to edit the
Apache configuration file.
Find the following lines and uncomment (remove the # at the beginning of the
lines) or add them if they don't exist:
LoadModule cgi_module modules/mod_cgi.so
AddHandler cgi-script .cgi .rb
ScriptInterpreterSource registry
Save the changes and close the editor.
Install cgi by using following command ====> gem install cgi
7. Create a CGI Script:
Open a text editor like Notepad or any code editor of your choice.
Write your CGI script. For example, let's create a simple script named hello.rb
that outputs a basic HTML page:

#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
name = "Dev"
puts cgi.header
puts "<html>"
puts "<head>"
puts "<title>CGI Ruby Example</title>"
puts "</head>"
puts "<body>"
puts "<h1>Hello, #{name.empty? ? 'Anonymous' : name}!</h1>"
puts "</body>"
puts "</html>"

Save the file in the cgi-bin directory within your XAMPP installation. For example,
you can save it in C:\xampp\cgi-bin.
8. Set Executable Permission:
Right-click on the hello.rb file, select "Properties," and then go to the "Security"
tab.
Click on "Edit" to change permissions, and make sure that "Read & execute" is
checked for the appropriate user group (e.g., Everyone).
9. Access the CGI Script via Web Browser:
Open a web browser and navigate to http://localhost/cgi-bin/hello.rb.
You should see the output of your CGI script displayed in the browser window.

Example 2:
Create html file in cgi-bin folder and name of the file is index.html
<!DOCTYPE html>
<head>
<title>CGI Ruby Example</title>
</head>
<body>
<h1>Enter Your Name</h1>
<form action="name.rb" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Create ruby file same folder i.e in cgi-bin and name it with name.rb
name.rb
#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
name = cgi['id']
puts cgi.header
puts "<html>"
puts "<head>"
puts "<title>CGI Ruby Example</title>"
puts "</head>"
puts "<body>"
puts "<h1>Hello, #{name.empty? ? 'Anonymous' : name}!</h1>"
puts "</body>"
puts "</html>"

Open any browser window and execute the html file http://localhost/cgi-bin/index.html

erb:
ERB stands for Embedded RuBy. It's a feature in Ruby that allows you to embed Ruby
code within a text document, typically used for generating dynamic content in web
applications. ERB is commonly used in web frameworks like Ruby on Rails for
generating HTML pages dynamically.
With ERB, you can write plain text documents (often HTML or XML) with snippets of
Ruby code embedded within <% %> or <%= %> tags. Here's a brief explanation of the
two main types of ERB tags:
<% %> (ERB scriptlet tags): These tags are used to embed Ruby code that doesn't
output anything directly to the document. They are typically used for control structures
like loops and conditionals.
<%= %> (ERB output tags): These tags are used to embed Ruby code that outputs a
value to the document. The result of the Ruby expression inside these tags will be
included in the output document.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<% if @logged_in %>
<p>Welcome back, <%= @username %>!</p>
<% else %>
<p>Welcome, Guest!</p>
<% end %>
</body>
</html>

Cookies:
cookies are small pieces of data that websites store on your device. They act like
memory for websites, enabling them to remember things about you and your browsing
activity.
Working of cookies:
1. Visiting a website: When you visit a website for the first time, the web server
may send your browser a cookie.
2. Storing the cookie: Your web browser stores the cookie information on your
device, typically in a file.
3. Subsequent visits: When you revisit the same website, your browser sends the
stored cookie back to the web server.
This exchange of cookies allows websites to:
❖ Maintain user sessions: Cookies can remember if you're logged in or not,
eliminating the need to re-enter credentials every time you visit a page.
❖ Personalize your experience: Websites can use cookies to tailor content and
functionality based on your preferences or past behavior. For instance, an e-
commerce site might use cookies to recommend products you might be
interested in.
❖ Track user behavior: Cookies can be used to track what pages you visit and how
you interact with a website. This data is often used for analytics purposes or
targeted advertising.

Example:
require 'cgi'
cgi = CGI.new
# Read the value of the 'username' cookie
username_cookie = cgi.cookies['Deepak']
puts cgi.header
if username_cookie.empty?
# Create cookie if it doesn't exist
new_cookie = CGI::Cookie.new('name' => 'Dev', 'value' => 'Guest', 'expires' => Time.now
+ 3600) # Expires in 1 hour
puts new_cookie
puts "Content-Type: text/html\n\n"
puts "<html>"
puts "<body>"
puts "<h1>Welcome, Guest!</h1>"
puts "<p>A 'Dev' cookie has been set.</p>"
puts "</body>"
puts "</html>"
else
# Greet user with stored username if cookie exists
username = username_cookie.first.value
puts "Content-Type: text/html\n\n"
puts "<html>"
puts "<body>"
puts "<h1>Welcome back, #{username}!</h1>"
puts "<p>You have returned to our site.</p>"
puts "</body>"
puts "</html>"
end
Choice of Web Servers:
WEBrick is a small, simple HTTP server toolkit that comes bundled with Ruby. It's often
used for development and testing purposes due to its ease of use and lightweight
nature. WEBrick is written in Ruby and provides a basic but functional web server that
can serve both static and dynamic content.
Here's a simple example of how you can use WEBrick to create a basic web server in
Ruby:
require 'webrick'
# Define a class for handling requests
class MyHandler < WEBrick::HTTPServlet::AbstractServlet
def do_GET(request, response)
# Set the response content type
response.content_type = 'text/plain'
# Set the response body
response.body = "Hello, World! You requested: #{request.path}"
# Send the response
response.status = 200
end
end
# Create a server instance
server = WEBrick::HTTPServer.new(Port: 8000)
# Mount the handler to respond to requests
server.mount '/', MyHandler
# Trap signals to gracefully shutdown the server
trap('INT') { server.shutdown }
# Start the server
server.start

We require the 'webrick' library to use the WEBrick server.

We define a class MyHandler that inherits from WEBrick::HTTPServlet::AbstractServlet. This class


overrides the do_GET method to handle GET requests. In this method, we set the content type,
response body, and status code.
We create a WEBrick::HTTPServer instance on port 8000.
We mount our handler class to the root path '/' so that it handles all requests to the server.
We set up a signal trap to gracefully shutdown the server when a SIGINT signal (e.g., Ctrl+C) is
received.
Finally, we start the server using server.start.

You can save this code in a file (e.g., simple_server.rb) and then run it using Ruby. After running the
script, open any browser and type the at http://localhost:8000 and see the response "Hello, World! You
requested: /".

SOAP Web Services:


Imagine you have two different software programs, each written in a different
language. Now, suppose you want these programs to talk to each other and share
data. This is where web services come in.
A web service acts like a middleman between these programs. It provides a way for
them to communicate over the internet.Types of Web Services: There are different
types of web services, but two common ones are:
❖ SOAP: This is more structured and formal, often used in enterprise
environments.
❖ REST: This is simpler and more flexible, often used for simpler interactions over
the web.
Example: Let's say you have a weather forecasting program written in Python and a
mobile app written in JavaScript. By using a web service, the app can ask the Python
program for the current weather data (like temperature and humidity). The Python
program processes this request and sends back the weather information in a format
that the app understands.
SOAP:
SOAP web services are a way for applications to communicate with each other over the
internet. Here's a breakdown of what SOAP stands for and how it works:
❖ SOAP stands for Simple Object Access Protocol. It's a set of rules that define
how messages are formatted and exchanged between applications.
❖ SOAP uses XML (Extensible Markup Language) for data exchange. XML
provides a structured way to represent data, making it understandable by
different applications regardless of their programming language.
● Key components in a SOAP web service:
○ Service Provider: This is the application that offers a specific
functionality or data. It exposes its services through a SOAP interface.
○ Service Requester: This is the application that wants to use the service
offered by the provider. It sends SOAP messages to the provider to
invoke the service and receive responses.
○ WSDL (Web Services Description Language): This is an optional
component that acts like a contract between the provider and requester.
It describes the service offered by the provider, including the functions
available, the expected data format, and the return values.

Here's a typical flow of how a SOAP web service works:

1. The service requester creates a SOAP message containing details about the
service it wants to invoke and any relevant data.
2. The SOAP message is sent to the service provider using HTTP (Hypertext
Transfer Protocol).
3. The service provider receives the SOAP message, parses the XML data, and
executes the requested service.
4. The service provider generates a response SOAP message containing the
results of the service execution.
5. The response message is sent back to the service requester using HTTP.
6. The service requester parses the response message and uses the extracted
data.

Advantages of SOAP web services:

● Platform and Language Independence: SOAP allows applications written in


different programming languages and running on various platforms to
communicate seamlessly.
● Security: SOAP provides mechanisms for implementing security features like
authentication and authorization.
● Standardization: SOAP is a well-established standard with wide industry support.

Disadvantages of SOAP web services:

● Complexity: SOAP messages can be complex and verbose due to the XML
structure, leading to increased processing overhead.
● Performance: Compared to simpler protocols like REST (Representational State
Transfer), SOAP can be slower due to the parsing of XML data.
● Steeper Learning Curve: Developing SOAP web services requires understanding
the SOAP protocol, XML, and potentially WSDL, which can have a steeper
learning curve.

RubyTk – Simple Tk Application


Tk:
In Ruby, Tk is a library that provides bindings to the Tk toolkit, a graphical user interface
(GUI) toolkit that originated as part of the Tcl scripting language. Tk allows you to
create and manipulate graphical user interfaces in your Ruby applications.
Here are some key points about Tk in Ruby:
GUI Development: Tk enables you to create graphical user interfaces for your Ruby
applications. You can create windows, buttons, labels, entry fields, menus, and other
GUI elements using Tk.
Cross-Platform: Tk is cross-platform, meaning that Tk-based Ruby applications can
run on different operating systems (Windows, macOS, Linux) without modification.
Event-Driven: Tk is event-driven, meaning that it responds to user actions such as
button clicks, mouse movements, and keyboard input. You can define callbacks to
handle these events and perform actions accordingly.
Widgets: Tk provides a wide range of widgets (GUI components) that you can use to
build your application's interface. These include buttons, labels, entry fields, text areas,
check buttons, radio buttons, listboxes, and more.
Layout Management: Tk provides facilities for laying out GUI components in your
application's windows. You can use geometry managers like pack, grid, and place to
arrange widgets in specific positions and sizes.

Applications of rubytk:
RubyTk shines in creating desktop applications with graphical user interfaces (GUIs)
for various purposes. Here are some common applications of RubyTk:
1. Develop basic productivity tools like calculators, note-taking apps, to-do list
managers, file launchers.
2. Create custom configuration or settings windows for other programs.
3. Design data visualization tools to display information in a user-friendly format
(charts, graphs).
4. Design data management interfaces for CRUD (Create, Read, Update, Delete)
operations on databases.

** Install tk library by using following command gem install tk

Example: Open notepad and the following code and save the file with tkexample.rb
Open command prompt and execute the ruby file
ruby tkexample.rb
require 'tk'
root = TkRoot.new { title "First Application" }
TkLabel.new(root) do
text 'Hello, World!'
pack('padx' => 15, 'pady' => 15, 'side' => 'left')
end
Tk.mainloop
Output:

Widgets
Widgets in Tk Ruby refer to the various graphical elements(Components) you can
create to build a graphical user interface (GUI) for your Ruby applications. These
widgets serve as the building blocks for creating interactive and visually appealing
interfaces. Some common widgets include buttons, labels, entry fields, checkboxes,
radio buttons, listboxes, and frames.
Each widget has its own set of properties and methods that allow you to customize its
appearance and behavior. For example, you can set the text displayed on a button,
define actions to be performed when a button is clicked, or specify the layout and
alignment of widgets within a window.
To create a Tk widget instance, add "Tk" to the widget's name, like TkLabel, TkButton,
or TkEntry, and then use the new method to initialize it.

Setting Widget Options


There are two ways to set options for widgets
1. Using a Hash: In Perl/Tk, options for widgets are usually passed as key-value
pairs within a Hash. For example, if you want to create a label widget with text
"Hello, World!" and specify padding and alignment, you would pass these options
as a Hash to the widget constructor.
Example:
TkLabel.new(parent_widget, 'text' => 'Hello, World!').pack('padx' => 5, 'pady' => 5, 'side'
=> 'left')
2. Using a Code Block: In Ruby, you can alternatively pass options using a code
block. Within the block, the option names are used as method names, and their
values are passed as arguments to these methods. This way, you can set the
options in a more Ruby-like manner.
TkLabel:
require 'tk'
root=TkRoot.new {title "Label"}
TkLabel.new(root)do
text "Username:"
pack
end
Tk.mainloop
Output:

TkEntry:
require 'tk'
root=TkRoot.new{title "entry"}
TkEntry.new(root){
width 30
pack('padx'=>300,'pady'=>10)
}
Tk.mainloop
Output:

TkButton:
require 'tk'
root=TkRoot.new{title "button example"}
TkButton.new(root){
text "Submit"
foreground 'red'
font TkFont.new(size:18,family:"Arial Black")
relief 'flat'
pack
}
Tk.mainloop
Output:

Distances (as in the padx and pady options in these examples) are assumed to
be in
pixels but may be specified in different units using one of the suffixes c
(centimeter), i
(inch), m (millimeter), or p (point). "12p", for example, is twelve points.
Getting Widget Data
We can get information back from widgets by using callbacks and by binding
variables.
Callbacks are very easy to set up.
Callback typically refers to a function or block of code that gets executed in
response to a specific user action or event, such as clicking a button, typing in a
text field, or selecting an item from a list.
For example, when you set up a callback for a button click event in Tk Ruby,
you're essentially specifying what code should be executed when the button is
clicked. This code is encapsulated within a Proc object and passed to the
command option of the TkButton widget. When the button is clicked, the
callback (i.e., the code specified in the Proc object) gets executed.
When an event, such as clicking a button, occurs in Tk Ruby, the Proc object
associated with the event (often specified using the command option) is indeed
responsible for executing the lines of code defined within it. So, in the case of a
button click event, the Proc object's responsibility is to execute the code
specified in the command option, which typically includes the actions to be
taken in response to the button click.
Example:
require 'tk'
TkButton.new do
text "EXIT"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
Tk.mainloop

Output: When the program is executed, it creates a window containing a button


labeled "EXIT". If you click the button, the window will be closed, thus
terminating the application.

Setting/Getting Options Dynamically


configure:
The configure method plays a crucial role in customizing the appearance and
behavior of widgets.It is used to change the properties of an existing Tk widget.

Common Options:
❖ text: Change the displayed text in labels, buttons, etc.
❖ font: Modify the font style and size.
❖ background: Set the background color.
❖ foreground: Set the text color.
❖ width: Define the width of the widget in pixels or characters.
❖ height: Define the height of the widget in pixels.
❖ state: Control the widget's state (e.g., :disabled, :normal).
❖ relief: Set the border style (e.g., :flat, :raised, :groove).

Example:
require 'tk'
root = TkRoot.new { title "Ex3" }
lbl = TkLabel.new(root) do
justify 'center'
text 'Hello, World!'
pack('padx'=>5, 'pady'=>5, 'side' => 'top')
end
TkButton.new(root) do
text "Ok"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
TkButton.new(root) do
text "Cancel"
command { lbl.configure('text'=>"Goodbye, Cruel World!") }
pack('side'=>'right', 'padx'=>10, 'pady'=>10)
end
Tk.mainloop
Output:
When we click on cancel the label content will be changed.

Geometry Management:
Geometry management refers to the process of arranging and positioning widgets
within a window. It plays a crucial role in defining the layout and visual structure of
your application. Tk provides three main geometry managers:
1. Pack
2. Grid
3. Place
Pack:
The pack geometry manager organizes widgets in rows or columns inside the
parent window or the widget. To manage widgets easily, the pack geometry
manager provides various options, such as fill, expand, and side.
Here is a simple syntax to create a pack Widget −
pack('padx'=>10, 'pady'=>10, 'side'=>'left')

Example:
require 'tk'
top = TkRoot.new {title "Label and Entry Widget"}
#code to add a label widget
lb1 = TkLabel.new(top) {
text 'Hello World'
background "yellow"
foreground "blue"
pack('padx'=>200, 'pady'=>50, 'side'=>'top')
}
#code to add a entry widget
e1 = TkEntry.new(top) {
background "red"
foreground "blue"
pack('padx'=>100, 'pady'=>10, 'side'=>'top')
}
Tk.mainloop

Output:

Grid:
The grid geometry manager is the most flexible and easy-to-use geometry manager.
It logically divides the parent window or the widget into rows and columns in a two-
dimensional table.
Syntax:
grid('row'=>x, 'column'=>y)
Example:
require 'tk'
# Create a Tk root window
root = TkRoot.new { title "Grid Layout Example" }
# Create labels
label1 = TkLabel.new(root) { text 'Label 1'; background 'red' }
label2 = TkLabel.new(root) { text 'Label 2'; background 'green' }
label3 = TkLabel.new(root) { text 'Label 3'; background 'blue' }
# Arrange labels using grid geometry manager
label1.grid('row' => 0, 'column' => 0)
label2.grid('row' => 0, 'column' => 1)
label3.grid('row' => 1, 'column' => 0)
# Start the Tk event loop
Tk.mainloop
Output:

Place:

The place geometry manager allows you to place a widget at the specified position in
the window. You can specify the position either in absolute terms or relative to the
parent window or the widget.
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
place(relx'=>x, 'rely'=>y)

Example:
require 'tk'
# Create a Tk root window
root = TkRoot.new { title "Place Layout Example" }
# Create labels
label1 = TkLabel.new(root) { text 'Label 1'; background 'red' }
label2 = TkLabel.new(root) { text 'Label 2'; background 'green' }
label3 = TkLabel.new(root) { text 'Label 3'; background 'blue' }
# Place labels using place geometry manager
label1.place('x' => 10, 'y' => 10)
label2.place('x' => 50, 'y' => 50)
label3.place('x' => 100, 'y' => 100, 'width' => 100, 'height' => 50)
# Start the Tk event loop
Tk.mainloop
Output:

Binding Events
"bind" refers to the process of associating an event with a specific action or callback
function. When an event occurs, such as a mouse click, keypress, or window resize, the
associated action or function is executed.
Syntax:
widget.bind(event, callback_function)
❖ widget: The widget to which the event is bound.
❖ event: The event to bind, specified as a string (e.g., "<Button-1>" for left mouse
click).
❖ callback_function: The function to be called when the event occurs.
Example:
require 'tk'
root=TkRoot.new
b=TkButton.new(root)do
text "Click here"
pack
end
l=TkLabel.new(root)do
text "This text will be changed"
pack
end
l.focus
b.command{l.configure(text:"changed")}
l.bind("Key-a"){l.configure(background:"red")}
Tk.mainloop

Canvas:

Canvas widget is used to draw graphical elements such as lines, rectangles, circles,
and text in a window.
Example:
require 'tk'
root = TkRoot.new
canvas = TkCanvas.new(root) do
width 300
height 200
background 'white'
pack
end
# Draw a rectangle (x,y,width,height)
rectangle = canvas.create('rectangle', 50, 50, 200, 150, fill: 'blue')
# Draw an oval()
oval = canvas.create('oval', 100, 100, 250, 200, fill: 'red')
# Draw a line
line = canvas.create('line', 20, 30, 200, 100, fill: 'green')
Tk.mainloop
Output:
Scrolling:
Scrolling in Ruby TK allows you to view content that's larger than the visible area of a
widget like a text box or a frame. Here's a breakdown of how it works:

The Widgets Involved:


❖ Scrollbar: This is a separate widget that displays a slider and arrows. By
dragging the slider or clicking the arrows, users can navigate through the hidden
content.
❖ Viewable Area: This is the portion of the main widget (text box, frame, etc.)
that's currently visible on the screen
Making it Work:
1. Creating the Scrollbar: You use the Tk::Scrollbar class to create a scrollbar
widget. You can customize its appearance using options like orient (vertical or
horizontal scrolling) and command (to link it with the viewable area).
2. Linking the Scrollbar: The command option in the scrollbar widget references
methods like xview or yview of the viewable area widget. These methods control
the visible portion of the content.
3. User Interaction: When the user interacts with the scrollbar (drags the slider or
clicks the arrows), the command option triggers the xview or yview methods in
the viewable area widget. These methods adjust the displayed content
accordingly.

require 'tk'
begin
root = TkRoot.new
text = TkText.new(root) { width 40; height 10 }
text.insert('end', "This is a much shorter text.\n" *100)
scroll_bar = TkScrollbar.new(root)
text.yscrollcommand(scroll_bar.method(:set))
scroll_bar.command(proc { |*args| text.yview(*args) })
scroll_bar.pack(side: 'right', fill: 'both', expand: true)
text.pack(side: 'left', expand: true, fill: 'both')
Tk.mainloop
end

You might also like