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.

1 Answer 1

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>"
Sign up to request clarification or add additional context in comments.

3 Comments

Myself, though, I'd go with Sinatra and Thin with Apache as a reverse proxy. But that's just me.
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.
See the link to the other question. Did you make the script +x, for example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.