Ruby provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols. These are documented in the next section.
Ruby also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on. These are documented starting in the section “.”
Finally, the CGI
libraries, documented in “CGI Development,” provide server-side developers with a convenient interface for developing Web applications.
Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest. All functionality in the socket library is accessible through a single extension library. Access it using
require 'socket'
Sockets have their own vocabulary:
PF_INET
, PF_UNIX
, PF_X25
, and so on.SOCK_STREAM
for connection-oriented protocols and SOCK_DGRAM
for connectionless protocols.INADDR_BROADCAST
address,
INADDR_ANY
, or
Integer
, interpreted as a binary address in host byte order.
Fixnum
port number, a string containing a port number, or the name of a service. Sockets are children of class IO
. Once a socket has been successfully opened, the conventional I/O methods may be used. However, greater efficiency is sometimes obtained by using socket-specific methods. As with other I/O classes, socket I/O blocks by default. The hierarchy of the socket classes is shown in Figure 26.1.
For more information on the use of sockets, see your operating system documentation. You'll also find a comprehensive treatment in W. Richard Stevens, Unix Network Programming, Volumes 1 and 2.
BasicSocket
is an abstract base class for all other socket classes.
This class and its subclasses often manipulate addresses using something called a struct sockaddr
, which is effectively an opaque binary string. (In reality, it maps onto the underlying C-language struct sockaddr
set of structures, documented in the man pages and in the books by Stevens.)
true
or false
true
, queries on remote addresses will return the
numeric address but not the host name.true
or false
Returns the global address lookup order, one of:
Order | Families Searched |
---|---|
LOOKUP_UNSP |
AF_UNSPEC |
LOOKUP_INET |
AF_INET , AF_INET6 , AF_UNSPEC |
LOOKUP_INET6 |
AF_INET6 , AF_INET , AF_UNSPEC |
nil
nil
struct sockaddr
structure associated with the other end of this socket connection.struct sockaddr
structure associated with aSession.struct sockaddr
specifying the recipient address. flags are the sum or one or more of the MSG_
options (listed under Socket
constants). Returns the number of characters sent.Socket
constants). optname and optval are protocol specific—see your system documentation for details.Class IPSocket
is a base class for sockets using IP as their transport. TCPSocket
and UDPSocket
are based on this class.
a = IPSocket.getaddress('www.ruby-lang.org')
a → "210.251.121.214"
do_not_reverse_lookup
flag is true
.
u = UDPSocket.new
u.bind('localhost', 8765)
u.addr → ["AF_INET", 8765, "localhost", "127.0.0.1"]
BasicSocket.do_not_reverse_lookup = true
u.addr → ["AF_INET", 8765, "127.0.0.1", "127.0.0.1"]
t = TCPSocket.new('localhost', 'ftp')
t.gets → "220 zip.local.thomases.com FTP server (Version 6.5/OpenBSD, linux port 0.3.2) ready.\r\n"
t.close → nil
AF_INET
), and the dotted-quad IP address.
a = TCPSocket.gethostbyname('ns.pragprog.com')
a → ["pragprog.com", [], 2, "216.87.136.211"]
TCPSocket.new
.MSG_
options (listed under Socket
constants). Returns a two-element array. The first element is the received data, the second is an array containing information about the peer.
t = TCPSocket.new('localhost', 'ftp')
data = t.recvfrom(30)
data
Class SOCKSSocket
supports connections based on the SOCKS protocol.
SOCKSSocket.new
.nil
A TCPServer
accepts incoming TCP connections. Here is a Web server that listens on a given port and returns the time.
require 'socket'
port = (ARGV[0] || 80).to_i
server = TCPServer.new('localhost', port)
while (session = server.accept)
puts "Request: #{session.gets}"
session.print "HTTP/1.1 200/OK\r\nContent-type: text/html\r\n\r\n"
session.print "<html><body><h1>#{Time.now}</h1></body></html>\r\n"
session.close
end
TCPServer.new
.TCPSocket
connected to the caller. See the example at the start of this class.UDP sockets send and receive datagrams. In order to receive data, a socket must be bound to a particular port. You have two choices when sending data: you can connect to a remote UDP socket and thereafter send datagrams to that port, or you can specify a host and port for use with every packet you send. This example is a UDP server that prints the message it receives. It is called by both connectionless and connection-based clients.
require 'socket'
$port = 4321
sThread = Thread.start do # run server in a thread
server = UDPSocket.open
server.bind(nil, $port)
2.times { p server.recvfrom(64) }
end
# Ad-hoc client
UDPSocket.open.send("ad hoc", 0, 'localhost', $port)
# Connection based client
sock = UDPSocket.open
sock.connect('localhost', $port)
sock.send("connection-based", 0)
sThread.join
produces:
["ad hoc", ["AF_INET", 33224, "localhost", "127.0.0.1"]]
["connection-based", ["AF_INET", 33225, "localhost", "127.0.0.1"]]
AF_INET
) → aSessionAF_INET
) → aSessionUDPSocket.new
.UDPSocket#send
requests that don't override the recipient will use this connection. Multiple connect
requests may be issued on aSession: the most recent will be used by send
.MSG_
options (listed under Socket
constants). The result is a two-element array containing the received data and information on the sender. See the example at the start of the documentation for this class.Class UNIXSocket
supports interprocess communications using the Unix domain protocol. Although the underlying protocol supports both datagram and stream connections, the Ruby library provides only a stream-based connection.
require 'socket'
$path = "/tmp/sample"
sThread = Thread.start do # run server in a thread
sock = UNIXServer.open($path)
s1 = sock.accept
p s1.recvfrom(124)
end
client = UNIXSocket.open($path)
client.send("hello", 0)
client.close
sThread.join
produces:
["hello", ["AF_UNIX", ""]]
UNIXSocket.new
.MSG_
options (listed under Socket
constants). The first element of the returned array is the received data, and the second contains (minimal) information on the sender.Class UNIXServer
provides a simple Unix domain socket server. See UNIXSocket
for example code.
UNIXServer.new
.UNIXSocket
.Class Socket
provides access to the underlying operating system socket implementation. It can be used to provide more operating system-specific functionality than the protocol-specific socket classes, but at the expense of greater complexity. In particular, the class handles addresses using struct sockaddr
structures packed into Ruby strings, which can be a joy to manipulate.
Class Socket
defines constants for use throughout the socket library. Individual constants are available only on architectures that support the related facility.
SOCK_DGRAM
, SOCK_PACKET
, SOCK_RAW
, SOCK_RDM
, SOCK_SEQPACKET
, SOCK_STREAM
.PF_APPLETALK
, PF_AX25
, PF_INET6
, PF_INET
, PF_IPX
, PF_UNIX
, PF_UNSPEC
.AF_APPLETALK
, AF_AX25
, AF_INET6
, AF_INET
, AF_IPX
, AF_UNIX
, AF_UNSPEC
.LOOKUP_INET6
, LOOKUP_INET
, LOOKUP_UNSPEC
.MSG_DONTROUTE
, MSG_OOB
, MSG_PEEK
.SOL_ATALK
, SOL_AX25
, SOL_IPX
, SOL_IP
, SOL_SOCKET
, SOL_TCP
, SOL_UDP
.SO_BROADCAST
, SO_DEBUG
, SO_DONTROUTE
, SO_ERROR
, SO_KEEPALIVE
, SO_LINGER
, SO_NO_CHECK
, SO_OOBINLINE
, SO_PRIORITY
, SO_RCVBUF
, SO_REUSEADDR
, SO_SNDBUF
, SO_TYPE
.SOPRI_BACKGROUND
, SOPRI_INTERACTIVE
, SOPRI_NORMAL
.IP_ADD_MEMBERSHIP
, IP_DEFAULT_MULTICAST_LOOP
, IP_DEFAULT_MULTICAST_TTL
, IP_MAX_MEMBERSHIPS
, IP_MULTICAST_IF
, IP_MULTICAST_LOOP
, IP_MULTICAST_TTL
.TCP_MAXSEG
, TCP_NODELAY
.getaddrinfo
error codes:EAI_ADDRFAMILY
, EAI_AGAIN
, EAI_BADFLAGS
, EAI_BADHINTS
, EAI_FAIL
, EAI_FAMILY
, EAI_MAX
, EAI_MEMORY
, EAI_NODATA
, EAI_NONAME
, EAI_PROTOCOL
, EAI_SERVICE
, EAI_SOCKTYPE
, EAI_SYSTEM
.ai_flags
values:AI_ALL
, AI_CANONNAME
, AI_MASK
, AI_NUMERICHOST
, AI_PASSIVE
, AI_V4MAPPED_CFG
.for line in Socket.getaddrinfo('www.microsoft.com', 'http')
puts line.join(", ")
end
produces:
AF_INET, 80, microsoft.net, 207.46.130.149, 2, 1, 6
AF_INET, 80, microsoft.net, 207.46.131.137, 2, 1, 6
AF_INET, 80, microsoft.com, 207.46.230.218, 2, 1, 6
AF_INET, 80, microsoft.com, 207.46.230.219, 2, 1, 6
AF_INET, 80, microsoft.net, 207.46.130.14, 2, 1, 6
AF_INET
) → anArraysockaddr
component for the given address.
a = Socket.gethostbyname("216.87.136.211")
res = Socket.gethostbyaddr(a[3], a[2])
res.join(', ') → "pragprog.com, , 2, \330W\210\323"
sockaddr
structure.
a = Socket.gethostbyname("216.87.136.211")
a.join(', ') → "pragprog.com, , 2, \330W\210\323"
nil
, it will be used as the host name. Returns a canonical hostname (or address) and port number as an array.
a = Socket.getnameinfo(["AF_INET", '23', 'www.ruby-lang.org'])
a → ["helium.ruby-lang.org", "telnet"]
'tcp'
) → aFixnumSocket.getservbyname("telnet") → 23
Socket.new
.Socket.pair
.Socket
object and a string holding the struct sockaddr
information about the caller.struct sockaddr
, contained in a string.struct sockaddr
, contained in a string.MSG_
options. The first element of the result is the data received. The second element contains protocol-specific information on the sender.Ruby provides a set of classes to facilitate writing clients for:
HTTP, POP, and SMTP are layered on top of a helper class, lib/net/protocol
. Although we don't document the Protocol
class here, you should probably study it if you are considering writing your own network client.
require 'net/ftp'
ftp = Net::FTP.new('ftp.netlab.co.jp')
ftp.login
files = ftp.chdir('pub/lang/ruby/contrib')
files = ftp.list('n*')
ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
ftp.close
net/ftp
library implements a File Transfer Protocol (FTP)
client.
FTP_PORT |
Default port for FTP connections (21). |
---|
nil
, user=nil
, passwd=nil
, acct=nil
) → aSessionFTP
object. If the host parameter is not nil
, a connection is made to that host. Additionally, if the user parameter is not nil
, the given user name, password, and (optionally) account are used to log in. See the description of FTP#login
.nil
, passwd=nil
, acct=nil
) → aSessionFTP.new
, but with a mandatory host parameter.nil
) → anArraytrue
or false
true
if the current connection is closed.SOCKS_SERVER
is set, sets up the connection through a SOCKS proxy. Raises an exception (typically Errno::ECONNREFUSED
) if the connection cannot be established.true
or false
true
or false
true
, all traffic to and from the server is written to $stdout.FTP#list
.nil
)nil
)nil
, acct=nil
) → aStringnil
, a password of user@host is synthesized. If the acct parameter is not nil
, an FTP ACCT
command is sent following the successful login. Raises an exception on error (typically Net::FTPPermError
).FTP#list
.false
) → aTimefalse
, or as a local time otherwise.true
or false
passive
flag.true
or false
true
.nil
)nil
)true
or false
FTP#resume=
). Default is false
.true
, partially received files will resume where they left off, instead of starting from the beginning again. This is done by sending a REST
command (REST
art incomplete transfer) to the server.nil
) Proc
, also passes it the data, in chunks of blocksize characters.nil
) Proc
, also passes it the lines.require 'net/http'
h = Net::HTTP.new('www.pragmaticprogrammer.com', 80)
resp, data = h.get('/index.html', nil )
puts "Code = #{resp.code}"
puts "Message = #{resp.message}"
resp.each {|key, val| printf "%-14s = %-40.40s\n", key, val }
p data[0..55]
produces:
Code = 200
Message = OK
last-modified = Wed, 29 May 2002 11:08:01 GMT
connection = close
content-type = text/html
etag = "804d98-255c-3cf4b691"
date = Sun, 09 Jun 2002 05:15:10 GMT
server = Rapidsite/Apa/1.3.20 (Unix) FrontPage/4.
content-length = 9564
accept-ranges = bytes
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional"
The net/http
library provides a simple client to fetch headers and Web page contents using the HTTP protocol.
The get
, post
, and head
requests raise exceptions on any error, including some HTTP status responses that would normally be considered recoverable. There are two ways of handling these.
get2
, post2
, or head2
that does not raise an exception. These versions are documented in the source.Net::ProtoRetriableError
exception. This exception contains a data
attribute containing the response returned by the server.The code below illustrates the handling of an HTTP status 301, a redirect. It uses Tomoyuki Kosimizu's URI package, available in the RAA.
h = Net::HTTP.new(ARGV[0] || 'www.ruby-lang.org', 80)
url = ARGV[1] || '/'
begin
resp, data = h.get(url, nil) { |a| }
rescue Net::ProtoRetriableError => detail
head = detail.data
if head.code == "301"
uri = URI.create(head['location'])
host = uri['host']
url = uri['path']
port = uri['port']
h.finish
h = Net::HTTP.new(host, port)
retry
end
end
nil
, proxy_port=nil
) → aSessionHTTP
object. No connection is made until HTTP#start
is called.nil
, port=80 )nil
, port=80 ) {| aSession | block }Net::HTTP.new(host, port).start
.nil
, dest="" ) → anArraynil
) {| result | block } → anArrayHash
containing additional header names and values to be sent with the request. The method returns a two-element array. The first element is an HTTPResponse
object (documented in the next section). The second element is the page's content. The page's content is also passed to the <<
method of the dest parameter, or to the block if specified. This result is built network block by network block, not line by line. An exception is raised if an error is encountered. Multiple get
calls may be made on aSession. Unless Protocol#finish
is explicitly called, the connection will use the HTTP/1.1 keep-alive protocol, and will not close between requests.nil
) → aHashhead
calls may be made on aSession.nil
, dest="" ) → anArraynil
) {| result | block } → anArrayNet_HTTP#get
. Returns a two-element array containing an HTTPResponse object and the reply body.start
is actually a method in Net::Protocol
, but its use is required in HTTP objects.) In the block form, closes the session at the end of the block.true
or false
true
only if a header with the given key exists.require 'net/pop'
pop = Net::POP3.new('server.ruby-stuff.com')
pop.start('user', 'secret') do |pop|
msg = pop.mails[0]
# Print the 'From:' header line
puts msg.header.split("\r\n").grep(/^From: /)
# Put message to $stdout (by calling <<)
puts "\nFull message:\n"
msg.all($stdout)
end
produces:
From: dummy msg for Andy
Full message:
From: dummy msg for Andy
looks-better: on dave's box
That's all folks!
The net/pop
library provides a simple client to fetch and delete mail on a Post Office Protocol (POP) server.
The class Net::POP3
is used to access a POP server, returning a list of Net::POPMail
objects, one per message stored on the server. These POPMail
objects are then used to fetch and/or delete individual messages. The library also provides an alternative to the POP3
class that performs APOP
authentication.
POP3
object. No connection is made until POP3#start
is called.POPMail
object.true
or false
false
if the connection was never used.POPMail
objects, where each object corresponds to an e-mail message stored on the server.POP3#mails
and POP3#each
methods. In block form, passes aSession to the block, and closes the connection using finish
when the block terminates.<<
for each line in the e-mail. With an associated block, invokes the block once for each line in the e-mail.POPMail#delete
.require 'net/smtp'
# — Send using class methods
msg = [ "Subject: Test\n", "\n", "Now is the time\n" ]
Net::SMTP.start do |smtp|
smtp.sendmail( msg, 'dave@localhost', ['dave'] )
end
# — Send using SMTP object and an adaptor
smtp = Net::SMTP.new
smtp.start('pragprog.com')
smtp.ready('dave@localhost', 'dave') do |a|
a.write "Subject: Test1\r\n"
a.write "\r\n"
a.write "And so is this"
end
The net/smtp
library provides a simple client to send electronic mail using the Simple Mail Transfer Protocol (SMTP).
SMTP
object connected to the given server and
port.nil
, passwd=nil
, authtype=:cram_md5 ) → aSessionnil
, passwd=nil
, authtype=:cram_md5 ) {| smtp | block }Net::SMTP.new(server, port).start(...)
. For an explanation of the remainder of the parameters, see the instance method Net_SMTP#start
. Creates a new SMTP
object. The domain parameter will be used in the initial HELO
or EHLO
transaction with the SMTP server. In the block form, the smtp object is passed into the block. When the block terminates, the session is closed.sendmail(from, to) { ...}
. Sends header and body lines to the sendmail server. The from parameter is used as the sender's name in the MAIL FROM:
command, and the to is either a string or an array of strings containing the recipients for the RCPT TO:
command. The block is passed an adaptor object. Lines are sent to the server by calling the adaptor's write
method. The terminating '.' and QUIT
are sent automatically.MAIL FROM:
command, and to is either a string or an array of strings containing the recipients for the RCPT TO:
command. Lines to be sent are fetched by invoking src.each
. The terminating '.' and QUIT
are sent automatically.nil
, passwd=nil
, authtype=:cram_md5 ) → true
or false
nil
, passwd=nil
, authtype=:cram_md5 ) {| smtp | block } → true
or false
:plain
or :cram_md5
). If a
block is supplied, it will be invoked with aSession as a
parameter. The connection will be closed when the block terminates.localhost
, run the “date” command, and disconnect.
require 'net/telnet'
tn = Net::Telnet.new({})
tn.login "guest", "secret"
tn.cmd "date" → "date\r\nSun Jun 9 00:15:20 CDT 2002\n\r> "
require 'net/telnet'
tn = Net::Telnet.new({}) { |str| print str }
tn.login("guest", "secret") { |str| print str }
tn.cmd("date") { |str| print str }
produces:
Trying localhost...
Connected to localhost.
Welcome to SuSE Linux 7.1 (i386) - Kernel 2.4.0-64GB-SMP (8).
zip login: guest
Password:
Last login: Sun Jun 9 00:15:19 from localhost
/etc/zshrc: setopt: no such option: histexpiredupsfirst [31]
> date
Sun Jun 9 00:15:20 CDT 2002
>
Get the time from an NTP server.
require 'net/telnet'
tn = Net::Telnet.new('Host' => 'time.nonexistent.org',
'Port' => 'time',
'Timeout' => 60,
'Telnetmode' => false)
atomicTime = tn.recv(4).unpack('N')[0]
puts "Atomic time: " + Time.at(atomicTime - 2208988800).to_s
puts "Local time: " + Time.now.to_s
produces:
Atomic time: Sun Jun 09 00:15:12 CDT 2002
Local time: Sun Jun 09 00:15:20 CDT 2002
The net/telnet
library provides a complete implementation of a telnet client and includes features that make it a convenient mechanism for interacting with non-telnet services.
Although the class description that follows indicates that Net::Telnet
is a subclass of class Socket
, this is a lie. In reality, the class delegates to Socket
. The net effect is the same: the methods of Socket
and its parent, class IO
, are available through Net::Telnet
objects.
The methods new
, cmd
, login
, and waitfor
take an optional block. If present, the block is passed output from the server as it is received by the routine. This can be used to provide realtime output, rather than waiting for (for example) a login to complete before displaying the server's response.
Hash
with zero or more of the following:
String | Standards Level | Meaning |
---|---|---|
Binmode |
false |
If true, no end-of-line processing will be performed. |
Host |
localhost | Name or address of server's host. |
Port |
23 | Name or number of service to call. |
Prompt |
/[$%#>]/ |
Pattern that matches the host's prompt. |
Telnetmode |
true |
If false , ignore the majority of telnet embedded escape sequences. Used when talking with a non-telnet server. |
Timeout |
10 | Time in seconds to wait for a server response (both during connection and during regular data transmission). |
Waittime |
0 | Time to wait for prompt to appear in received data stream. |
true
or false
Binmode
flag.true
or false
Binmode
flag, returning the new value.Hash
, it is sent as a string to the server, and the pattern to match and the timeout are the Prompt
and Timeout
options given when aSession was created. If options is a Hash
, then options['String'] is sent to the server. options['Match'] may be used to override the class Prompt
parameter, and options['Timeout'] the timeout. The method returns the complete server response.Hash
, a username is taken from options['Name'] and a password from options['Password']; otherwise, options is assumed to be the username, and password the password. The method waits for the server to send the string matching the pattern /login[:‿]*\z/
and sends the username. If a password is given, it then waits for the server to send /Password[:‿]*\z/
and sends the password. The method returns the full server response.Telnetmode
, Binarymode
, and any additional modes negotiated with the server.true
or false
Telnetmode
flag.true
or false
Telnetmode
flag, returning the new value.Waits for the server to respond with a string that matches a string or pattern. If options is not a Hash
, it is compared against the cumulative server output as that output is received using options.===
. It is likely that you will want to use a regular expression in this case.
If options is a Hash
, then options['Match'], options['Prompt'], or options['String'] provides the match. In the latter case, the string will be converted to a regular expression before being used. options may also include the keys “Timeout” and “Waittime” to override the class options of the same names.
require "cgi"
cgi = CGI.new("html3") # add HTML generation methods
cgi.out {
CGI.pretty (
cgi.html {
cgi.head { cgi.title{"TITLE"} } +
cgi.body {
cgi.form {
cgi.textarea("get_text") +
cgi.br +
cgi.submit
} +
cgi.h1 { "This is big!" } +
cgi.center { "Jazz Greats of the 20" +
cgi.small {"th"} + " century" + cgi.hr
} + cgi.p + cgi.table ('BORDER' => '5') {
cgi.tr { cgi.td {"Artist"} + cgi.td {"Album"} } +
cgi.tr { cgi.td {"Davis, Miles"} +
cgi.td {"Kind of Blue"} }
}
}
}
) # CGI.pretty is a method call, not a block
}
(The output of this script is shown in Figure 26.2.)
The CGI
class provides support for programs used as a Web server CGI (Common Gateway Interface) script. It contains several methods for accessing fields in a CGI form, manipulating “cookies” and the environment, and outputting formatted HTML.
Since environment variables contain a lot of useful information for a CGI script, CGI
makes accessing them very easy—environment variables are accessible as attributes of CGI
objects. For instance, cgi.auth_type
returns the value of ENV["AUTH_TYPE"]
. To create the method name, the environment variable name is translated to all lowercase, and the “HTTP_
” prefix is stripped off. Thus, HTTP_USER_AGENT
would be available as the method user_agent
.
Cookies are represented using a separate object of class CGI::Cookie
, containing the following accessors:
Accessor | Description |
---|---|
name |
Name of this cookie |
value |
Array of values |
path |
Path (optional) |
domain |
Domain (optional) |
expires |
Time of expiry, defaults to Time.now (optional) |
secure |
true for a secure cookie |
You create a cookie object using CGI_Cookie.new
, which takes as arguments the accessors listed above, or CGI_Cookie.parse
, which takes an encoded string and returns a cookie object.
print CGI::escapeElement('<BR><A HREF="url"></A><P>', "A", "IMG")
produces:
<BR><A HREF="url"></A><P>
&
”,“"
”,“<
”,“>
”) quoted using “&
”, “"
”, “<
”, “>
”, and so on.CGI
object. If HTML output is required, the desired standards level must be given in aString (otherwise, no output routines will be created). The level may be one of:
String | Standards Level | String | Standards Level |
---|---|---|---|
“html3” | HTML 3.2 | “html4” | HTML 4.0 Strict |
“html4Tr” | HTML 4.0 Transitional | “html4Fr” | HTML 4.0 Frameset |
Mon, 1 Jan 2001 00:00:00 GMT
).Array
. See the note on multipart forms.Hash
object containing key-value pairs of cookie keys and values.true
or false
true
if the form contains a field named aString.MOD_RUBY
environment, the resulting header is sent immediately instead). If a hash is given as an argument, then the key-value pairs will be used to generate headers.nil
nil
CGI#header
. See the example at the start of this section.Hash
object containing key-value pairs of field names and values from the form.In addition, CGI
supports the following HTML output methods. Each of these methods is named after the corresponding HTML feature (or close to it). Those tags that require content (such as blockquote
) take an optional block; the block should return a String
that will be used as the content for the feature. These methods may take arguments as indicated, or as a hash with the given names as keys.
a
( url )a
( HREF
⇒ )base
( url )base
( HREF
⇒ )blockquote
( cite="" ) { aString }blockquote
( CITE
⇒ ) { aString }caption
( align=nil ) { aString }caption
( ALIGN
⇒ ) { aString }checkbox
( name=nil
, value=nil
, checked=nil
)checkbox
( NAME
, VALUE
, CHECKED
⇒ )checkbox_group
( name=nil
, [items]+ )checkbox_group
( NAME
, VALUES
⇒ )String
names, or any of: an array of [ name, checked ], an array of [ value, name ], or an array of [ value, name, checked ]. The value for the hash key VALUES should be an array of these items.file_field
( name="", size=20, maxlength=nil
)file_field
( NAME
, SIZE
, MAXLENGTH
⇒ )form
( method="post", action=nil
, enctype="application/x-www-form-urlencoded" ) { aStr }form
( METHOD
, ACTION
, ENCTYPE
⇒ ) { aStr }hidden
( name="", value=nil
)hidden
( NAME
, VALUE
⇒ )html
( ) { aString }html
( PRETTY
, DOCTYPE
⇒ ) { aString }img_button
( src="", name=nil
, alt=nil
)img_button
( SRC
, NAME
, ALT
⇒ )img
( src="", alt="", width=nil
, height=nil
)img
( SRC
, ALT
, WIDTH
, HEIGHT
⇒ )multipart_form
( action=nil
, enctype="multipart/form-data" ) { aString }multipart_form
( METHOD
, ACTION
, ENCTYPE
⇒ ) { aString }password_field
( name="", value=nil
, size=40, maxlength=nil
)password_field
( NAME
, VALUE
, SIZE
, MAXLENGTH
⇒ )popup_menu
( name="", items )popup_menu
( NAME
, SIZE
, MULTIPLE
, VALUES
(array of items) ⇒ )String
names, or any of: an array of [ name, selected ], an array of [ value, name ], or an array of [ value, name, selected ]. The value for the hash key VALUES should be an array of these items. radio_button
( name="", value=nil
, checked=nil
)radio_button
( NAME
, VALUE
, CHECKED
⇒ )radio_group
( name="", items )radio_group
( NAME
, VALUES
(array of items) ⇒ )String
names, or any of: an array of [ name, selected ], an array of [ value, name ], or an array of [ value, name, selected ]. The value for the hash key VALUES should be an array of these items.reset
( value=nil
, name=nil
)reset
( VALUE
, NAME
⇒ )scrolling_list
( alias for popup_menu )scrolling_list
( ⇒ )submit
( value=nil
, name=nil
)submit
( VALUE
, NAME
⇒ )text_field
( name="", value=nil
, size=40, maxlength=nil
)text_field
( NAME
, VALUE
, SIZE
, MAXLENGTH ⇒ )textarea
( name="", cols=70, rows=10 )textarea
( NAME
, COLS
, ROWS
⇒ )In addition, all HTML tags are supported as methods, including title
, head
, body
, br
, pre
, and so on. The block given to the method must return a String
, which will be used as the content for that tag type. Not all tags require content: <P>
, for example, does not. The available tags vary according to the supported HTML level—Table 26.1 lists the complete set. For these methods, you can pass in a hash with attributes for the given tag. For instance, you might pass in 'BORDER'=>'5'
to the table
method to set the border width of the table.
{HTML 3} | {HTML 4} | {HTML 4 Transitional} | {HTML 4 Frameset} |
---|---|---|---|
a address applet area b base basefont big blockquote body br caption center cite code dd dfn dir div dl dt em font form h1 h2 h3 h4 h5 h6 head hr html i img input isindex kbd li link listing map menu meta ol option p param plaintext pre samp script select small strike strong style sub sup table td textarea th title tr tt u ul var xmp |
a abbr acronym address area b base bdo big blockquote body br button caption cite code col colgroup dd del dfn div dl dt em fieldset form h1 h2 h3 h4 h5 h6 head hr html i img input ins kbd label legend li link map meta noscript object ol optgroup option p param pre q samp script select small span strong style sub sup table tbody td textarea tfoot th thead title tr tt ul var |
a abbr acronym address applet area b base basefont bdo big blockquote body br button caption center cite code col colgroup dd del dfn dir div dl dt em fieldset font form h1 h2 h3 h4 h5 h6 head hr html i iframe img input ins isindex kbd label legend li link map menu meta noframes noscript object ol optgroup option p param pre q s samp script select small span strike strong style sub sup table tbody td textarea tfoot th thead title tr tt u ul var |
HTML 4 Transitional plus:frame frameset |
When dealing with a multipart form, the array returned by CGI#[]
is composed of objects of class Tempfile
, with the following dynamically added methods:
Method | Description |
---|---|
read |
Body |
local_path |
Path to local file containing the content |
original_filename |
Original filename of the content |
content_type |
Content type |
A CGI::Session
maintains a persistent state for web users in a CGI environment. Sessions may be memory-resident or may be stored on disk. See the discussion on “Sessions” for details.
Returns a new session object for the CGI
query. Options that may be given in aHash include:
Option | Description |
---|---|
session_key |
Name of CGI key for session identification. |
session_id |
Value of session id. |
new_session |
If true , create a new session id for this session. If false , use an existing session identified by session_id . If omitted, use an existing session if available, otherwise create a new one. |
database_manager |
Class to use to save sessions; may be CGI::Session::FileStore or CGI::Session::MemoryStore (or user defined if you're brave). Default is FileStore . |
tmpdir |
For FileStore, directory for session files. |
prefix |
For FileStore, prefix of session filenames. |
delete
method of the underlying database manager. For FileStore
, deletes the physical file containing the session. For MemoryStore
, removes the session from memory.update
method of the underlying database manager. For FileStore
, writes the session data out to disk. Has no effect with MemoryStore
.Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.