text 18 Nov Use Ruby like PHP

E se volessimo usare Ruby come PHP? Senza Rails o qualche strano framework?
Vediamo come fare con Apache…
Per prima cosa installiamo Apache2

apt-get install apache2

Andiamo ad abilitare l’esecuzione dei CGI con i seguenti comandi:

a2enmod cgid
a2enmod actions

Modifichiamo il file /etc/apache2/sites-available/default e aggiungiamo:

<Directory /var/www/>
  AddHandler rubypage .rhtml
  Action rubypage /erb.cgi
  AddHandler cgi-script .cgi
  Options Indexes FollowSymLinks MultiViews ExecCGI
  AllowOverride None
  Order allow,deny
  Allow from all
</Directory>

Bene, ora riavviamo apache con /etc/init.d/apache2 restart.
Ora copiano il seguente codice nel file che creerete in /var/www/erb.cgi:

#!/usr/bin/ruby

require 'time'
require 'erb'

time = Time.now.httpdate

HEADERS = <<EOF
Date: #{ time }
Server: #{ ENV['SERVER_SOFTWARE'] }
Last-Modified: #{ time }
Content-Type: text/html

EOF

begin

  path = nil
  if (ENV['PATH_TRANSLATED'])
    path = ENV['PATH_TRANSLATED']
  else
    file_path = ENV['REDIRECT_URL'].include?(File.basename(__FILE__)) ?     ENV['SCRIPT_URL'] : ENV['REDIRECT_URL']
    path = File.expand_path(ENV['DOCUMENT_ROOT'] + '/' + file_path)
    raise "Attempt to access invalid path: #{path}" unless     path.index(ENV['DOCUMENT_ROOT']) == 0
  end
  erb = File.open(path) { |f| ERB.new(f.read) }
  print HEADERS + erb.result(binding)

rescue Exception

  print "Content-Type: text/html\n\n"

  # error message
  print "<h1>Script Error</h1>"
  print "<pre>#{ $! }</pre>"

  # debug info
  print "<h2>Backtrace</h2>"
  print "<pre>#{$!.backtrace.join("\n")}</pre>"

  print "<h2>Environment</h2>"
  print "<pre>#{ENV.keys.map { |key| key + ' = ' + ENV[key] + "\n"} }</pre>"

  print "<hr>"
  print "<i>#{__FILE__} -- #{time}</i>"

end

Bene! Ricordiamo i permessi chmod 755 /var/www/erb.cgi

Infine creiamo il nostro file in Ruby (/var/www/test.rhtml):

<%= 'Hello World' %>
<strong>YEAH</strong>

Visitiamo http://localhost/test.rhtml


blog comments powered by Disqus