John Breedlove
John Breedlove

Reputation: 425

process html form submission with ruby to modify local file on server

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.

Upvotes: 2

Views: 1407

Answers (1)

Phrogz
Phrogz

Reputation: 303261

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>"

Upvotes: 1

Related Questions