| home | forums |
resources |
search |
news | join | members: 6370 |
Hiveminds | Sun, 2006-12-24 07:49 tags: Tutorials, Web Developer, eRuby Ruby is a great language to use to create a dynamic website. Here's how to use it to do CGI scripting. Using eRuby ERB templating to seperate the HTML from the script makes CGI a perfect alternative to using the Rails framework. Easy and faster than you would expect. There are many templating systems around the web. Most of them for languages like Perl are a real pain to deal with. They use strange syntax and the tutorials that describe how to use them are horribly nerdy. This makes it difficult to get started for beginners. But don't worry I am not going to do that here. What I will show you is a simple script to get you started. Then it is up to you to get going to learn more. I am going to use the Ruby ERB templating system because it is the one that is used in Rails. If you have a Rails hoster then ERB should be installed by default. The first thing you are going to have to is find a new web host or question your web hosting company about running Ruby scripts as CGI. You can always run things locally on your PC but where the fun in that? The usual file ending is .rb. I say this because I have checked three Rails hosters and found that all three had problems running a plain CGI script. I had to email each one and wait for that magic moment when my "hello world" testing worked. Once that was done the rest was cake. Using a .htaccess file you may have to add the file ending .rb. This is so that it will execute as a CGI script rather than showing as plain text. Don't forget to set file permissions on the *.rb file so that it can be executed. Chmod to 774 should be okay for most hosting situations. AddHandler cgi-script .rb Options +ExecCGI The traditional methodThe normal way of creating web pages using CGI pretty much sucks. When you want to make layout changes you have to wade through miles of complicated code to find the HTML you need to change. Below is a simple example of how HTML is traditionally embedded in a CGI script. #!/usr/bin/env ruby print "HTTP/1.0 200 OK\r\n" print "Content-type: text/html\r\n\r\n" print "<html><body>Hello World!</body></html>\r\n" Helper methodsIf you imagine thousands of lines of the previous code the you will see the problem. Ruby does have a CGI library which tries to ease the burden. But to be honest it is more confusing than a help. The syntax and code layout is not natural. require "cgi"
cgi = CGI.new("html3") # add HTML generation methods
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
}
}
}
}
A better wayTo get around that nasty bit of mess we can use templating. First you want to create a simple CGI script and save it to a *.rb file. #!/usr/lib/ruby/
# We are going to use erubis for templating rather than ERB
require 'erb'
#CGI is needed for headers. Without it the the output may default to plain text
require 'cgi'
# set a new object
cgi = CGI.new("html3")
# print header type
print cgi.header("type"=>"text/html")
# show usage of CGI HTML in the template
headline = cgi.h1 { "A page: " } + "\n" + cgi.hr
# read the template file. The name can be anything but we use "eruby" to avoid confusion.
input = File.read('example1.eruby')
# mix the template (input from above) and this file to create the eRuby object
eruby = ERB.new(input)
# Create some Ruby code that can be outputed to the template page
list = ['aaa', 'bbb', 'ccc','ddd','your name']
name = ' A list of items 2'
# Print the result of the two files.
puts eruby.result(binding())
# call this file in your browser
Good and bad coding stylesNotice that there is no HTML in the above file. There is not even a print statement containing a HTML tag. The HTML will come from the template below. There is an exception in the code. I did this to demonstrate first, what not to do when coding. Secondly to give a practical example of what was mentioned earlier about finding HTML within script code and the difficulties that it brings. # show usage of CGI HTML in the template
headline = cgi.h1 { "A page: " } + "\n" + cgi.hr
Notice that the header H1 and the HR tag do appear in the result. But if I wanted to adjust them or eliminate them they are not in the template file where they should be. Located in the CGI file they are hard to recognize even in a simple script like this one. So I repeat, do not practice this kind of coding style. It is always avoidable. Making the code XHTML compliantAnother thing that happens when using the built-in scripting of HTML is the HTML is not correct. Notice that the H1 and HR tags are capitals. A throw back from 1999 and not valid xhtml. There is a patch to Ruby CGI for this that brings it up to xhtml 1.0 standards but I have no idea if it has been commited. Besides Dreamhost is still running Ruby 1.8.2. Hmm, getting sidetracked here. Here's the code for the template file. example1.eruby <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<%= headline %>
Name:<%= name %>
<ul>
<% for item in list %>
<li><%= item %></li>
<% end %>
<%# here is ignored because starting with '#'
but each line must start with a # or the interpreter will stop %>
</ul>
</body>
</html>
ConclusionHere's a demo of the output of the above code running at Dreamhost. Here's where I start advocating the use of eRuby and eRuby web hosting. Be sure to check with your service providers to make sure they are supporting the use of Ruby as CGI properly. Many hosting companies while jumping through hoops to get Rails installed have not bothered to check on the simpler usages of Ruby. Also if your hosting provider does not do Rails then you might want to ask them about installing Ruby and providing support for CGI programming. You can do a lot with Ruby without Rails and it is so much easier than Perl. If you are a PHP programmer that uses templating you'll find eRuby a very tempting alternative to PHP and Smarty like packages.
This article brought to you by the
Hiveminds Magazine - Staff. Contact us if you want to post an article or announcement anonymously |
Content Management Systems London Hotels
eRuby Laptop Reviews
Content Management Systems Just Dial International Calls
Content Management Systems Excel Training Courses
Windows excel courses in london
Adobe Flex Joomla! Data Recovery
|
||||||
NewsletterGet updates on Hiveminds services, articles and downloads by signing up for the newsletter. |
Editor's choiceSome of the better articles, stories and tutorials found at Hiveminds. |
Find moreFind more of Hiveminds articles, stories, tutorials and user comments by searching. |
Picked linksHand picked websites and articles from around the web that provide quality reading. |