Simple mod_ruby counter using global variable

I'm guessing this is because each Apache process has its own Ruby interpreter instance:

The following code inside a mod_ruby script does not always increment $total displayed in the browser (it actually increments $total internally, but each time the page is refreshed, the next Apache process is used in seemingly round-robin fashion):

···

-----
if defined?($total)
     $total = $total + 1
else
     $total = 0
end
puts "total = #{$total}"
-----

Does anyone know the simplest way to deal with this other than using persistent storage like database or file?

You could run your application as a stand-alone server and have your CGI call
it, but that would be a little more involved than simply tracking the total
through a file or database.

  Sean O'Dell

···

On Friday 02 July 2004 13:29, Randy Lawrence wrote:

I'm guessing this is because each Apache process has its own Ruby
interpreter instance:

The following code inside a mod_ruby script does not always increment
$total displayed in the browser (it actually increments $total
internally, but each time the page is refreshed, the next Apache process
is used in seemingly round-robin fashion):

-----
if defined?($total)
     $total = $total + 1
else
     $total = 0
end
puts "total = #{$total}"

I would use the Application or Session objects in the Ruby::ASP environment.

Or at least look at how it is handled there.

Randy Lawrence wrote:

···

I'm guessing this is because each Apache process has its own Ruby interpreter instance:

The following code inside a mod_ruby script does not always increment $total displayed in the browser (it actually increments $total internally, but each time the page is refreshed, the next Apache process is used in seemingly round-robin fashion):

-----
if defined?($total)
    $total = $total + 1
else
    $total = 0
end
puts "total = #{$total}"
-----

Does anyone know the simplest way to deal with this other than using persistent storage like database or file?

A file would work, but you'd have to be careful to lock it before each
write, or you could lose updates. It might be better to run a
single-purpose 'counting server' listening on a socket, which
maintained an internal count variable, and incremented and echoed it
across the wire every time a client connected. It's more work than
just setting a global, but no persistence is involved, and you don't
have to worry about race conditions -- just handle the requests on a
first-come, first-served basis.

Lennon