2

Given the following example html form:

<html> 
  <head> 
    <title>Sure wish I understood this. :)</title> 
  </head> 
  <body>
    <p>Enter your data:</p>
      <form method="POST" action="bar.rb" name="form_of_doom"> 
        <input type="text" name="data">
        <input type="submit" name="Submit" value="Submit"> 
      </form> 
  </body> 
</html>

What would "bar.rb" look like to write the submission to a text file on the server? I am running apache, but I am trying to avoid databases and rails.

John Breedlove
  • 405
  • 1
  • 4
  • 14

1 Answers1

1

You need some way to invoke the Ruby file as a result of the web request, and to pass in all form data to the script.

It looks like you can do that with Apache by treating Ruby scripts as CGI. Quoting:

DocumentRoot /home/ceriak/ruby

<Directory /home/ceriak/ruby>
    Options +ExecCGI
    AddHandler cgi-script .rb
</Directory>

At this point you can use the CGI library that ships with Ruby to handle the parameters:

#!/usr/bin/ruby -w                                                                                                           

# Get the form data
require 'cgi'
cgi = CGI.new
form_text = cgi['text']

# Append to the file
path = "/var/tmp/some.txt"
File.open(path,"a"){ |file| file.puts(form_text) }

# Send the HTML response
puts cgi.header  # content type 'text/html'
puts "<html><head><title>Doom!</title></head><body>"
puts "<h1>File Written</h1>"
puts "<p>I wrote #{path.inspect} with the contents:</p>"
puts "<pre>#{form_text.inspect}</pre>"
puts "</body></html>"
Community
  • 1
  • 1
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • Myself, though, I'd go with [Sinatra](http://sinatrarb.com) and [Thin](http://code.macournoyer.com/thin/) with Apache as a reverse proxy. But that's just me. – Phrogz Jun 03 '13 at 03:56
  • The script is not executing, it is just displaying in the browser. I made sure it was executable, but I think I am not getting Apache to obey me. I will look into Sinatra and Thin. Thanks for the quick reply. – John Breedlove Jun 03 '13 at 05:05
  • See the link to the other question. Did you make the script +x, for example? – Phrogz Jun 03 '13 at 05:14