Ruby Source Code: fwrite.rb
#!/usr/bin/ruby
require 'cgi'
require './common'
#----------------------------------------------------------
# The Web Language Project
# Mark Brautigam
# May-June 2015
# http://www.mixed-up.com/markb/
#----------------------------------------------------------
cgi = CGI.new
puts cgi.header
headers1()
headers2()
print sidebarX("ruby", "fwrite", "rb")
print %q(
<div id="content">
<h2>Ruby: Form Handling and Write to File</h2>
<form name='coursesform' action='fwrite.rb' method='POST'>
<fieldset>
<legend>Add a course</legend>
<table>
<tr><td>College:</td><td><input type='text' name='college' /></td></tr>
<tr><td>Department:</td><td><input type='text' name='dept' /></td></tr>
<tr><td>Course #:</td><td><input type='text' name='course' /></td></tr>
<tr><td>Course name:</td><td><input type='text' name='desc' /></td></tr>
<tr><td></td><td><input type='submit' id='submit' name='submit' value='Add' /></td></tr>
</table>
</fieldset>
</form>
)
#----------------------------------------------------
# The main Ruby code is here.
#----------------------------------------------------
college = cgi['college']
dept = cgi['dept']
course = cgi['course']
desc = cgi['desc']
submit = cgi['submit']
if ((submit == 'Add') && (formHasData([college, dept, course, desc])))
print "<p>The following data was entered in the data file: </p>\n";
print "<table class='results'>\n";
printf( " <tr><td>College</td><td>%s</td></tr>", college)
printf( " <tr><td>Department</td><td>%s</td></tr>", dept)
printf( " <tr><td>Course #</td><td>%s</td></tr>", course)
printf( " <tr><td>Course name</td><td>%s</td></tr>", desc)
print "</table>"
# Beware. The print function above includes CR by default.
# BUT the fp.write function below does not include the CR.
fp = File.new('../data/courses.txt', 'a')
dataToWrite = sprintf("%s|%s|%s|%s\n", college,dept,course,desc)
# print (dataToWrite) # debug
fp.write (dataToWrite)
fp.close
end
#----------------------------------------------------
print %q(
<p><a href='fread.rb'>Show the contents of this file »</a></p>
<p><a href='source.rb?f=3'>Show Ruby source code »</a>
</div>
)
footers()