Serg said:
Hi,
Does anyone have a solution to calling a Ruby method when someone
clicks on the Submit button of an HTML form (without Rails)? And
an ancillary question, is there a way to catch the form input into
Ruby variables? My understanding is that the action element needs
to invoke the server side logic which is a bother if you want to
get form input and pre-process it.
Thanks!
You can use Ruby exactly as you would use other languages such as
Perl to do this. For instance, place your Ruby script in the cgi-bin
directory, set up the web server to know that .rb or .cgi maps to
ruby (differs depending on OS and web server), and then write your
script. Set the post method of the form to be the URL of your
script. Use the Ruby CGI library (
http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/index.html
) that handles a lot of the details for you.
This section I pasted below is from the CGI docs regarding form
inputs and Ruby variables. From this it should be clear that passing
form parameters into Ruby variables is trivial.
-Jim
Parameters
The method params() returns a hash of all parameters in the request
as name/value-list pairs, where the value-list is an Array of one or
more values. The CGI <
http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html
object itself also behaves as a hash of parameter names to values,
but only returns a single value (as a String) for each parameter name.
For instance, suppose the request contains the parameter
"favourite_colours" with the multiple values "blue" and "green". The
following behaviour would occur:
cgi.params["favourite_colours"] # => ["blue", "green"]
cgi["favourite_colours"] # => "blue"
If a parameter does not exist, the former method will return an
empty array, the latter an empty string. The simplest way to test
for existence of a parameter is by the has_key? method.