newbie-Ruby
just for fun and to provide a very new service to our customers, handgestrickt learned Ruby recently. the syntax is simple, highly structured, clearly readable, yet powerful. for people who are used to read cryptic Perl-scripts, Ruby is a real delight.
in the next weeks we will have a look at Ruby On Rails.
inspite of using the Apache mod_ruby to make our Ruby-scripts running on the webserver, we just run them as CGI-scripts by adding the following to the Apache-configuration:
<IfModule mod_mime.c>
AddHandler cgi-script .cgi .rb
</IfModule>
we do not want to hide our first efforts. the following script reads out the current folder and outputs it to the browser. you can click on a file or folder to open it.
#!/usr/bin/ruby
class Folderview
#requiring and including necessary modules
require "erb"
include ERB::Util
require "cgi"
#constructor
def initialize(folder = nil)
#default values
@folders = []
@files = []
@folder = "./"
@cgi_folder = ""
#if a folder is passed
if !folder.nil?
@folder = add_slash(folder)
end
#add the current cgi-values
@cgi = CGI.new
if @cgi.has_key?("folder")
@folder += add_slash(@cgi["folder"])
@cgi_folder = add_slash(@cgi["folder"])
end
#read the folder data
read_data
end
#reads the folder data and pushes it into the related arrays
def read_data
folder = Dir.new(@folder)
while data = folder.read
if data !~ /^\./
if File.directory?(@folder+data)
@folders.push(data)
elsif File.file?(@folder+data)
@files.push(data)
end
end
end
folder.close
end
#output the whole HTML-tree in <pre>-tags
def output_html
puts "Content-Type: text/html\n\n"
puts "<pre>\n"
output_folders
output_files
puts "</pre>\n"
end
#outputs the folders one by one
def output_folders
@folders.each do |folder|
puts "<a href=\"#{ENV["SCRIPT_NAME"]}?folder=#{url_encode(@cgi_folder+folder)}\">#{html_escape(folder)}</a>\n";
end
end
#outputs the files one by one
def output_files
@files.each do |file|
puts "<a href=\"#{@folder}#{url_encode(file)}\">#{html_escape(file)}</a>\n";
end
end
#adds a slash to folder names if necessary
def add_slash(folder)
if folder !~ /\/$/
folder += "/"
end
return folder
end
#access rules
public :initialize, :output_html
private :add_slash, :read_data, :output_folders, :output_files
end
view = Folderview.new
view.output_html
exit

