While loops

If I have this snippet of code for the main page that loads:

def index
while 1
logger.info(“hi”)
end
end

Then, I close the browser that opened that page, I notice that the
logger continues to print “hi” to the file (using tail -f). Is there a
way to stop the server from running such actions when the browser is
closed? (The logger.info was just an example. It could be anything
else)

Thanks

“Erich L.” [email protected] writes:

way to stop the server from running such actions when the browser is
closed? (The logger.info was just an example. It could be anything
else)

Thanks

When you close a page showing on the browser, the browser may or may
not close the connection to your server. If it does not, then you
can’t tell whether a page has been closed.

If it does, then you have to perform IO operation to detect the
closing.

If you really care, you could surround the critical code with guard
code that tries to detect connection closing (IO::select for
read-readyness and performing IO#sysread(nonzero length) on such IO
object returns a 0-length string).

But there is still no fool-proof way to detect a user closing a
page. (Not even using javascript to handle window close event since
that won’t be invoked when the browser is closed).

YS.

I assume you are talking about a Rails app. index() should NOT run
forever like that. It should generate the page and return. If you want
to keep updating someting, “pull” information from the browser using
JavaScript (make the while loop in JavaScript).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs