Ruby 简明教程
Ruby Web Applications - CGI Programming
Ruby 是一种通用语言;它根本不能准确地称为 Web 语言。尽管如此,Web 应用程序和通用 Web 工具仍然是 Ruby 最常见的用途之一。
Ruby is a general-purpose language; it can’t properly be called a web language at all. Even so, web applications and web tools in general are among the most common uses of Ruby.
您不仅可以使用 Ruby 编写自己的 SMTP 服务器、FTP 守护程序或 Web 服务器,还可以将 Ruby 用于更常用的任务,例如 CGI 编程或作为 PHP 的替代方案。
Not only can you write your own SMTP server, FTP daemon, or Web server in Ruby, but you can also use Ruby for more usual tasks such as CGI programming or as a replacement for PHP.
请花几分钟时间参阅 CGI Programming 教程,以更详细地了解 CGI 编程。
Please spend few minutes with CGI Programming Tutorial for more detail on CGI Programming.
Writing CGI Scripts
最基本的 Ruby CGI 脚本如下所示 −
The most basic Ruby CGI script looks like this −
#!/usr/bin/ruby
puts "HTTP/1.0 200 OK"
puts "Content-type: text/html\n\n"
puts "<html><body>This is a test</body></html>"
如果您调用此脚本 test.cgi 并以正确的权限将其上传到基于 Unix 的 Web 托管服务提供商,您可以将其用作 CGI 脚本。
If you call this script test.cgi and uploaded it to a Unix-based Web hosting provider with the right permissions, you could use it as a CGI script.
例如,如果您有一个托管在 Linux Web 托管服务提供商上的名为 https://www.example.com/ 的网站,并且您已将 test.cgi 上传到主目录并授予它执行权限,那么访问 https://www.example.com/test.cgi 时应该会返回一个显示 This is a test 的 HTML 网页。
For example, if you have the Web site https://www.example.com/ hosted with a Linux Web hosting provider and you upload test.cgi to the main directory and give it execute permissions, then visiting https://www.example.com/test.cgi should return an HTML page saying This is a test.
在此,当 Web 浏览器请求 test.cgi 时,Web 服务器会在网站上查找 test.cgi,然后使用 Ruby 解释器执行它。此 Ruby 脚本会返回一个基本的 HTTP 头,然后返回一个基本的 HTML 文档。
Here when test.cgi is requested from a Web browser, the Web server looks for test.cgi on the Web site, and then executes it using the Ruby interpreter. The Ruby script returns a basic HTTP header and then returns a basic HTML document.
Using cgi.rb
Ruby 自带一个名为 cgi 的特殊库,它支持比之前的 CGI 脚本更复杂的操作。
Ruby comes with a special library called cgi that enables more sophisticated interactions than those with the preceding CGI script.
让我们创建一个使用 cgi 的基本 CGI 脚本 −
Let’s create a basic CGI script that uses cgi −
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
puts cgi.header
puts "<html><body>This is a test</body></html>"
此处,您创建了一个 CGI 对象并使用它为您打印头行。
Here, you created a CGI object and used it to print the header line for you.
Form Processing
使用类 CGI 使您可以通过两种方式访问 HTML 查询参数。假设我们提供了一个 URL /cgi-bin/test.cgi?FirstName = Zara&LastName = Ali。
Using class CGI gives you access to HTML query parameters in two ways. Suppose we are given a URL of /cgi-bin/test.cgi?FirstName = Zara&LastName = Ali.
按照以下方法直接使用 CGI#[] 访问 FirstName 和 LastName 参数:
You can access the parameters FirstName and LastName using CGI#[] directly as follows −
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi['FirstName'] # => ["Zara"]
cgi['LastName'] # => ["Ali"]
访问这些表单变量还有另一种方法。以下代码会给你一个所有键值对的哈希值:
There is another way to access these form variables. This code will give you a hash of all the key and values −
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
h = cgi.params # => {"FirstName"=>["Zara"],"LastName"=>["Ali"]}
h['FirstName'] # => ["Zara"]
h['LastName'] # => ["Ali"]
以下代码用于检索所有键:
Following is the code to retrieve all the keys −
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi.keys # => ["FirstName", "LastName"]
如果表单包含具有相同名称的多个字段,则相应的键值对将作为数组返回给脚本。[] 访问器仅返回这些值中的第一个。对 params 方法的结果进行索引用以获取所有键值对。
If a form contains multiple fields with the same name, the corresponding values will be returned to the script as an array. The [] accessor returns just the first of these.index the result of the params method to get them all.
在此示例中,假设表单有三个名为“姓名”的字段,我们输入了三个姓名“Zara”、“Huma”和“Nuha”:
In this example, assume the form has three fields called "name" and we entered three names "Zara", "Huma" and "Nuha" −
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi['name'] # => "Zara"
cgi.params['name'] # => ["Zara", "Huma", "Nuha"]
cgi.keys # => ["name"]
cgi.params # => {"name"=>["Zara", "Huma", "Nuha"]}
Note - Ruby 将自动处理 GET 和 POST 方法。这两个不同的方法没有单独的处理。
Note − Ruby will take care of GET and POST methods automatically. There is no separate treatment for these two different methods.
可以发送正确数据的相关但基本的表单具有如下 HTML 代码:
An associated, but basic, form that could send the correct data would have the HTML code like so −
<html>
<body>
<form method = "POST" action = "http://www.example.com/test.cgi">
First Name :<input type = "text" name = "FirstName" value = "" />
<br />
Last Name :<input type = "text" name = "LastName" value = "" />
<input type = "submit" value = "Submit Data" />
</form>
</body>
</html>
Creating Forms and HTML
CGI 包含大量用于创建 HTML 的方法。每个标签都有一个方法。为了启用这些方法,你必须通过调用 CGI.new 创建一个 CGI 对象。
CGI contains a huge number of methods used to create HTML. You will find one method per tag. In order to enable these methods, you must create a CGI object by calling CGI.new.
为了简化标签嵌套,这些方法将内容用作代码块。代码块应该返回一个字符串,该字符串将用作标签的内容。例如:
To make tag nesting easier, these methods take their content as code blocks. The code blocks should return a String, which will be used as the content for the tag. For example −
#!/usr/bin/ruby
require "cgi"
cgi = CGI.new("html4")
cgi.out {
cgi.html {
cgi.head { "\n"+cgi.title{"This Is a Test"} } +
cgi.body { "\n"+
cgi.form {"\n"+
cgi.hr +
cgi.h1 { "A Form: " } + "\n"+
cgi.textarea("get_text") +"\n"+
cgi.br +
cgi.submit
}
}
}
}
NOTE - CGI 类的 form 方法可以接受一个方法参数,该参数将设置提交表单时要使用的 HTTP 方法 (GET、POST 等)。本示例中使用的默认值为 POST。
NOTE − The form method of the CGI class can accept a method parameter, which will set the HTTP method ( GET, POST, and so on…) to be used on form submittal. The default, used in this example, is POST.
这会产生以下结果 −
This will produce the following result −
Content-Type: text/html
Content-Length: 302
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">
<HTML>
<HEAD>
<TITLE>This Is a Test</TITLE>
</HEAD>
<BODY>
<FORM METHOD = "post" ENCTYPE = "application/x-www-form-urlencoded">
<HR>
<H1>A Form: </H1>
<TEXTAREA COLS = "70" NAME = "get_text" ROWS = "10"></TEXTAREA>
<BR>
<INPUT TYPE = "submit">
</FORM>
</BODY>
</HTML>
Quoting Strings
在处理 URL 和 HTML 代码时,你必须小心引用某些字符。例如,斜杠字符 (/) 在 URL 中具有特殊含义,因此当它不是路径名的一部分时,必须 escaped 。
When dealing with URLs and HTML code, you must be careful to quote certain characters. For instance, a slash character ( / ) has special meaning in a URL, so it must be escaped if it’s not part of the pathname.
例如,URL 查询部分中的任何 / 都将转换为字符串 %2F,并且你必须将其转换回 / 才能使用它。空格和与号也是特殊字符。为了解决此问题,CGI 提供了例程 CGI.escape 和 CGI.unescape 。
For example, any / in the query portion of the URL will be translated to the string %2F and must be translated back to a / for you to use it. Space and ampersand are also special characters. To handle this, CGI provides the routines CGI.escape and CGI.unescape.
#!/usr/bin/ruby
require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl")
这会产生以下结果 −
This will produce the following result −
Zara+Ali%2FA Sweet+%26+Sour+Girl")
#!/usr/bin/ruby
require 'cgi'
puts CGI.escapeHTML('<h1>Zara Ali/A Sweet & Sour Girl</h1>')
这会产生以下结果 −
This will produce the following result −
<h1>Zara Ali/A Sweet & Sour Girl</h1>'
Useful Methods in CGI Class
以下列出了 CGI 类相关方法:
Here is the list of methods related to CGI class −
-
The Ruby CGI − Methods related to Standard CGI library.
Cookies and Sessions
我们在不同的部分中解释了这两个概念。请遵循以下部分:
We have explained these two concepts in different sections. Please follow the sections −
-
The Ruby CGI Cookies − How to handle CGI Cookies.
-
The Ruby CGI Sessions − How to manage CGI sessions.