Unit 1 Web
Unit 1 Web
UNIT I
RUBY
Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is scripting language?
• Scripting language (also known as scripting, or
script) is a series of commands that are able
to be executed without the need for
compiling and is rather interpreted one by
one at runtime.
[Eg.] Ruby, Python, Java Script
Uses of scripting language
• Scripting language (also known as scripting, or
script) is a series of commands that are able
to be executed without the need for
compiling.
Characteristics of scripting language
• It is open-source, which means a user can have
full control to view and edit it.
• It is easy to learn and work with.
• Comparatively faster to develop than an actual
program.
• It has a limited number of data structures which
makes it easy to write and edit.
• The language is beneficial to bring interactivity in
web pages.
• It helps in creating new applications in web
browsers.
• It is used to create plug-ins and extensions.
Advantages of scripting language
• Easy learning: The user can learn to code in scripting
languages quickly, not much knowledge of web
technology is required.
• Fast editing: It is highly efficient with the limited
number of data structures and variables to use.
• Interactivity: It helps in adding visualization interfaces
and combinations in web pages. Modern web pages
demand the use of scripting languages. To create
enhanced web pages, fascinated visual description
which includes background and foreground colors and
so on.
• Functionality: There are different libraries which are
part of different scripting languages. They help in
creating new applications in web browsers and are
different from normal programming languages.
Disadvantages of scripting language
• It enables users to view the scripts.
• It need to install an interpreter or separate
program by the users before running the
script.
• Scripting languages may be slow in some
situations.
Applications of scripting language
• Scripting languages are used in web applications.
It is used in server side as well as client side.
Server side scripting languages are: JavaScript,
PHP, Perl etc. and client side scripting languages
are: JavaScript, AJAX, jQuery etc.
• Scripting languages are used in system
administration. For example: Shell, Perl, Python
scripts etc.
• It is used in Games application and Multimedia.
• It is used to create plugins and extensions for
existing applications.
Types of Scripting Language
UNIT I
The structure and
Execution of Ruby
Programs
Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
Structure of Ruby Programs
• The structure of Ruby programs is explained
as:
– Lexical Structure
– Syntactic Structure
– File Structure
– Program Encoding
– Program Execution
Lexical Structure
• The Ruby interpreter parses a program as a
sequence of tokens.
• Tokens include
– comments
– literals
– punctuation
– identifiers
– keywords
Comments
• A Ruby comment adds information to the
code that is helpful for the developers.
• Comments in Ruby begin with a # character
and continue to the end of the line.
• The Ruby interpreter ignores the # character
and any text that follows it.
Comments
• If a # character appears within a string or
regular expression literal, then it is simply
part of the string or regular expression and
does not introduce a comment.
[Eg.]
# This entire line is a comment
x = "#This is a string" # And this is a comment
y = /#This is a regular expression/ # Here's another comment
Comments Types
Comment Types
Embedded Documentation
Documents Comments
Single line comments
• An identifier is a name.
• Ruby uses identifiers to name variables,
methods, classes.
• Ruby identifiers consist of letters, numbers,
and underscore characters, but they may not
begin with a number.
• Identifiers may not include whitespace or
nonprinting characters or punctuation
characters.
Identifiers
• An identifier is a name.
• Identifiers that begin with a capital letter A–Z are
constants, and the Ruby interpreter will issue a
warning if you alter the value of such an
identifier.
• Class and module names must begin with initial
capital letters.
[Eg.]
i
x2
old_value
_internal # Identifiers may begin with underscores
PI # Constant
Case sensitivity
Kinds of Blocks
Blocks Body
Block
Ways of declaring
Blocks
1.upto(10) do |x|
print x
End
Output:
1 2 3 4 5 6 7 8 9 10
Inline between the curly braces {}
Example:
3.times { print "Ruby! " }
Output:
Ruby! Ruby! Ruby!
Body
UNIT I
Package
Management with
RUBYGEMS
Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is Ruby Gems?
• RubyGems is a package manager for Ruby
libraries.
• RubyGems is used to deal with installation,
removal, updates of Ruby libraries.
• RubyGems libraries are called Gems for short.
Facilities in Ruby Gems
• It provides users and developers with four main
facilities.
– A standardized package format
– A central repository for hosting packages in this
format
– Installation and management of multiple,
simultaneously installed versions of the same
library
– End-user tools for querying, installing, uninstalling,
and otherwise manipulating these packages
Why Ruby Gems?
Operator Description
= Exact version match. Major, minor, and patch level must be
identical.
!= Any version that is not the one specified.
> Any version that is greater (even at the patch level) than the one
specified.
< Any version that is less than the one specified.
>= Any version greater than or equal to the specified version.
<= Any version less than or equal to the specified version.
~> “Boxed” version operator. Version must be greater than or equal
to the specified version and less than the specified version after
having its minor version number increased by one.
Installing Application Gems - older
version of Rake
• During installation, you can also add the t
option to the RubyGems install command,
causing RubyGems to run the gem’s test suite
(if one has been created).
• If the tests fail, the installer will prompt you to
either keep or discard the gem.
% gem install SomePoorlyTestedProgram t
Attempting local installation of SomePoorly TestedProgram1.0.1'
Successfully installed SomePoorlyTestedProgram, version 1.0.1
23 tests, 22 assertions, 0 failures, 1 errors...keep Gem? [Y/n] n
Successfully uninstalled SomePoorlyTestedProgram version 1.0.1
What is test suite?
• Test suite is a collection of tests which can be
run.
Installing and Using Gem Libraries
• RubyGems is used to install Ruby libraries
• find and install the BlueCloth gem.
• % gem query rn Blue
*** REMOTE GEMS ***
BlueCloth (0.0.4, 0.0.3, 0.0.2)
BlueCloth is a Ruby implementation of Markdown, a texttoHTML
conversion tool for web writers. Markdown allows you to write using
an easytoread,
easytowrite
plain text format, then convert it
to structurally valid XHTML (or HTML).
UNIT I
Ruby and Web:
Writing CGI Scripts
Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is Ruby in Web?
• Ruby is a server-side scripting language.
• Ruby can be used to write Common Gateway
Interface (CGI) scripts.
• Ruby can be embedded into Hypertext Markup
Language (HTML).
• Ruby has a clean and easy syntax that allows a
new developer to learn very quickly and easily.
What is CGI?
Output:
Content-type: text/html
<html><body>Hello World! It's 2022-03-27 15:05:42
+0000</body></html>
Writing CGI Scripts
• If Web server doesn’t automatically add headers,
add the response header.
[Example]
#!/usr/bin/ruby
print "HTTP/1.0 200 OK\r\n"
print "Content-type: text/html\r\n\r\n"
print "<html><body>Hello World! It's
#{Time.now}</body></html>\r\n"
Output:
HTTP/1.0 200 OK
Content-type: text/html
<html><body>Hello World! It's 2022-03-27 15:08:39
+0000</body></html>
Using cgi.rb
Example:
require 'cgi'
puts CGI.escape("Nicholas Payton/Trumpet &
Flugel Horn")
Output
Nicholas+Payton%2FTrumpet+%26+Flugel+Horn
Quoting
require 'cgi'
puts CGI.escapeHTML("a < 100 && b > 200")
Output:
a < 100 && b > 200
Quoting
• To escape only certain HTML elements within a
string.
require 'cgi'
puts CGI.escapeElement('<hr><a href="/mp3">Click
Here</a><br>','A')
Output:
<hr><a href="/mp3">Click
Here</a><br>
require 'cgi‘
puts CGI.unescapeHTML("a < 100 && b > 200")
Output:
a < 100 && b > 200
Query Parameters
require 'cgi'
cgi = CGI.new
cgi['name'] → "Dave Thomas"
cgi['reason'] → "flexible"
Query Parameters
require 'cgi'
cgi = CGI.new
cgi['name'] → "Dave Thomas"
cgi['reason'] → "flexible"
Query Parameters
require 'cgi'
cgi = CGI.new
cgi.params → {"name"=>["Dave Thomas"],
"reason"=>["flexible", "transparent",
"fun"]}
cgi.params['name'] →["Dave Thomas"]
cgi.params['reason'] → ["flexible",
"transparent", "fun"]
cgi.params['name'] = [ cgi['name'].upcase ]
cgi.params → {"name"=>["DAVE THOMAS"],
"reason"=>["flexible", "transparent","fun"]}
Query Parameters
require 'cgi'
cgi = CGI.new
cgi.has_key?('name') → true
cgi.has_key?('age') → false
Generating HTML
Syntax:
erb can be invoked as
erb [ options ] [ document ]
Expression Description
<% ruby code %> Execute the Ruby code
between the delimiters.
<%= ruby expression Evaluate the Ruby expression,
%> and replace the sequence with
the expression’s value.
<%= ruby expression The Ruby code between the
%> delimiters is ignored
% line of ruby code A line that starts with a percent
is assumed to contain just Ruby
code
Using erb – Command-line options
Option Description
-d Sets $DEBUG to true
-Kkcode Specifies an alternate encoding
system
-n Display resulting Ruby script
-r library Loads the named library
-P Doesn’t do erb processing on lines
starting %
-S level Sets the safe level
-T mode Sets the trim mode
-v Enables verbose mode
-x Displays resulting Ruby script
Erb – Example
% a = 99
<%= a %> Pack of Apples
</ul>
<h1>"Environment variables starting with "T"</h1>
<table>
%ENV.keys.grep(/^T/).each do |key|
<tr><td><%=key%></td><td><%=ENV[key]%></td<
</tr>
%end
</table>
</body>
</html>
Ruby embedded in HTML
Output:
<!DOCTYPE HTML PUBLIC "//
W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>eruby example</title>
</head>
<body>
<h1>Enumeration</h1>
<ul>
<li>number 0</li>
<li>number 1</li>
<li>number 2</li>
<li>number 3</li>
<li>number 4</li>
</ul>
Ruby embedded in HTML
<h1>"Environment variables starting with "T"</h1>
<table>
<tr><td>TERM_PROGRAM</td><td>Apple_Terminal<
/td></tr>
<tr><td>TERM</td><td>xtermcolor</
td></tr>
<tr><td>TERM_PROGRAM_VERSION</td><td>133</t
d></tr>
<tr><td>TYPE</td><td>SCREEN</td></tr>
</table>
</body>
</html>
Installing eruby in Apache
#!/usr/bin/ruby
require 'webrick'
include WEBrick
s = HTTPServer.new(
:Port => 2000,
:DocumentRoot => File.join(Dir.pwd, "/html")
)
trap("INT") { s.shutdown }
s.start
Choice of Web Servers - Example
UNIT I
RUBY Tk
Dr.D.Magdalene Delighta
Angeline
III CSE Associate Professor-CSE
JBREC
What is Ruby Tk?
require 'tk'
root = TkRoot.new { title "Ex1" }
TkLabel.new(root) do
text 'Hello, World!'
pack('padx' => 15, 'pady' => 15, 'side' => 'left')
end
Tk.mainloop
Simple Tk Application
• After loading the tk extension module, create a
root-level frame using TkRoot.new.
• Then make a TkLabel widget as a child of the root
frame, setting several options for the label.
• Finally, pack the root frame and enter the main
GUI event loop.
Widgets
• A widget is an element of a Graphical User
Interface (GUI) that displays information or
provides a specific way for a user to interact with
the operating system or an application.
• Widgets include icons, pull-down menus, buttons,
selection boxes, progress indicators, on-off
checkmarks, scroll bars, windows, window edges
(that let you resize the window), toggle buttons,
form, and many other devices for displaying
information and for inviting, accepting, and
responding to user actions.
• In Ruby Tk, create an instance of a widget using
new.
Setting Widget Options
• The name of the option is used as a method name within the block
and arguments to the option appear
as arguments to the method call.
Widgets take a parent as the first argument, followed by an optional
hash of options or the code block of options. Thus, the following two
forms are equivalent.
TkLabel.new(parent_widget) do
text 'Hello, World!'
pack('padx' => 5,
'pady' => 5,
'side' => 'left')
end
# or
TkLabel.new(parent_widget, 'text' => 'Hello, World!').pack(...)
Setting Widget Options
• A widget is an element of a Graphical User
Interface (GUI) that displays information or
provides a specific way for a user to interact with
the operating system or an application.
• Widgets include icons, pull-down menus, buttons,
selection boxes, progress indicators, on-off
checkmarks, scroll bars, windows, window edges
(that let you resize the window), toggle buttons,
form, and many other devices for displaying
information and for inviting, accepting, and
responding to user actions.
• In Ruby Tk, create an instance of a widget using
new.
Setting Widget Options
TkLabel.new(parent_widget) do
text 'Hello, World!'
pack('padx' => 5,'pady' => 5,'side' => 'left')
end
# or
require 'tk'
TkButton.new do
text "EXIT"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
Tk.mainloop
Getting Widget Data
require 'tk'
packing = { 'padx'=>5, 'pady'=>5, 'side' => 'left' }
checked = TkVariable.new
def checked.status
value == "1" ? "Yes" : "No"
end status = TkLabel.new do
text checked.status
pack(packing)
end
TkCheckButton - Example
TkCheckButton.new do
variable checked
pack(packing)
end
TkButton.new do
text "Show status"
command { status.text(checked.status) }
pack(packing)
end
Tk.mainloop
Setting/Getting Options Dynamically