Ruby, CGI and HTML Forms

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

Test

First Name

Last Name

Please reenter

Welcome #{first} #{last}. HTML

Latest change to include conditional statement:

#!/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

Test

First Name

Last Name

Please reenter

Welcome #{first} #{last`}.

HTML

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 “

Please re-enter


else
puts “

Welcome etc…


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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs