CGI and Methods?

Hi all,

I’m trying my hand at scripting cgi in ruby. At the same time I’m
looking at Rails. So far I love ruby. Still reserving comments on
Rails. I have a question though. When coding a cgi script, is it
possible to have methods as I would say in a n my_app.rb or rails app?
Below is a script I’m working on to provide a web interface to our
syslog servers logs for our tech support dept. I would like to DRY this
up a bit. I’m repeating entirely too much code. I would welcome not
only a response to my question, but any other suggestions/criticism to
aid me in my learning process. Thank you very much.

tonyd

#!/usr/local/bin/ruby -w

Filename: syssearch.cgi

Description:

Open log(s) file and do our searching before we begin to send

data back to the browser. This way we don’t cause the browser to time

out

(in theory…)

Inputs: none

require ‘cgi’

cgi = CGI.new

Our search params passed

search_string = cgi[‘searchit’]
slogtype = cgi[‘logtype’]
smethod = cgi[‘method’]

Do we have something to search on?

if search_string.empty?
puts “Content-type: text/plain\r\n\r\n\n\nCommSpeed
Log Search\n\n\n”
puts “

Please enter a search criteria


puts “\n\n”
exit
end

A hash of possible logs

logs = {‘smtp’ => ‘smtp’, ‘mail’ => ‘maillog’, ‘mx’ => ‘mx’, ‘spam’ =>
‘spam’, ‘Dial Up’ => ‘radius’, ‘DHCP’ => ‘dhcp’ }

if smethod == “CAT”

Array to hold our search result matches

results = Array.new

Open file and look for our search string

File.open("/var/log/"+logs[slogtype],
‘r’).grep(/#{search_string}/).each do |line|
results.push(line) # append it to our results array
end # file is automatically closed

if results.empty?
# No matches found
puts “Content-type:
text/plain\r\n\r\n\n\nCommSpeed Log
Search\n\n\n”
puts “

No DHCP Log Results Found!


puts “\n\n”
exit
else
# Now send results back to browser
puts “Content-type:
text/plain\r\n\r\n\n\nCommSpeed Log
Search\n\n\n”
puts “

DHCP Log Results…

  # Print the results
  results.each do |line|
    puts line+"<br>"
  end

# Close HTML
puts "</BODY>\n</HTML>\n"
            exit

end
end

if smethod == “TAIL”
#TODO
#Need to figure out how to tail a file with out search scope in place
and feed it to the browser window.
end