|
To quote Wikipedia, "CGI is a protocol for interfacing external applications to web servers. CGI applications run in a separate process, which is created at the start of each request and torn down at the end."
You can get yourself more familiar with the concepts here if it's the first time you hear about CGI and you can read more about fastCGI here
The Ruby class CGI offers support for writing CGI scripts.An interesting implementation of cgi in Ruby is the eRuby ERB templating system.
Without the templating system, if you were to create a web page using regular cgi, things could easily get out of control because of the large amounts of code you need to write.
Here's how a simple cgi created html page could look:
#!/usr/bin/ruby
# test.cgi
puts "Content-Type: text/html"
puts
puts "<html>"
puts "<body>"
puts "<h1>Hello World!</h1>"
puts "</body>"
puts "</html>"
Here's how a simple cgi created html page could look when created in Ruby:
#!/usr/bin/ruby
# test.cgi
require 'cgi'
cgi = CGI.new("html4")
cgi.out {
cgi.html {
cgi.body {
cgi.h1 { "Hello World!" }
}
}
}
After a few more lines like these you'll have problems reading and figuring out your own code; the main problem is the fact that it's written in a very systematic, unnatural way...it doesn't seem to be easy to interpret as a language.
Here's how a smarte cgi script saved in a Ruby script file can get you out of trouble:
#!/usr/lib/ruby/
require 'erb'
require 'cgi'
cgi = CGI.new("html4")
print cgi.header("type"=>"text/html")
headline = cgi.h1 { "Hello world!" } + "\n" + cgi.hr
input = File.read('test.eruby')
eruby = ERB.new(input)
.................
puts eruby.result(binding())
So here are some basic concepts of cgi in Ruby:
escaping/unescaping special characters:
require 'cgi'
puts CGI.escape("black/white")
A few more other samples:
|