Ruby, CGI and HTML Forms

R

Ray Trounday

I a new to Ruby and CGI scripts. I have developed a test CGI script to
collect a first and last name. I would like to echo the first and last
name if it is submitted correctly or prompt user to reenter if that is
not the case.


This is what I have so far:

#!/usr/local/bin/ruby

require 'cgi'
cgi = CGI.new

first = cgi['first_name']
last = cgi['last_name']
puts "Content-type: text/html"
puts


puts <<HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<body>
<form action="" method="post" accept-charset="utf-8">
<p>
<label for="First Name" style="width:100px;float:left">First
Name</label>
<input type="text" name="first_name" value="" id="first_name">
</p>
<p>
<label for="Last Name" style="width:100px;float:left">Last Name</label>
<input type="text" name="last_name" value="" id="last_name">
<p>
<p><input type="submit" value="Continue &rarr;"></p>
</form>

<p>Please reenter </p>


<p> Welcome #{first_name} #{last_name}.
</body>


</html>
HTML
 
B

Brian Candler

Looks like you've started off fine.

The bit between <<HTML and HTML is just one big long string ('HTML' is
the terminator), so the conditional bit has to be outside it(*)

puts <<HTML
.. page header and other stuff
HTML
if first == "" || last == ""
puts "<p>Please re-enter</p>"
else
puts "<p>Welcome etc...</p>"
end
puts <<HTML
.. page footer
HTML

When you've realised this is an ugly way to write even small web apps,
google for "ruby sinatra" for a better way.

Regards,

Brian.

(*) Actually I lied - you can embed expressions inside #{...}. It's not
a good idea to do it here though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top