Re: How to keep persistent socket connections?

Jonathan Rochkind
Sat, 30 May 2009 18:04:38 -0000

Steve Hull wrote:

> Yeah, that didn''t work because caching the connection makes it
> immutable, which means you can no longer write data to it.  But you know
> what I think *will* work?  Storing the connection(s) as class vars.  So
> I''m trying that next.  I will report back here afterward for
anyone who
> might be interested.

I''d use a singleton object (ruby Singleton module lets you do this
easily, or it''s easy enough to do yourself) that encapsulates logic and
state for your ''connection pool'', rather than class variables.
But
you''re on the right track.

Note though that you''ve got to make sure all your logic (in this case
in
that hypothetical Singleton object), is concurrency-safe, if your rails
app can possibly be deployed in any kind of a concurrent-request
environment (or if you plan to create Threads yourself in your rails
app, but hardly anyone ever does that).

You could look at the newish Rails 2.2 ActiveRecord ConnectionPool for a
model, since it''s doing basically what you want, but specifically for
db
connections. The ConnectionPool code might just end up being too
confusing and complicated though, since it has to deal with Rails
backwards compatibility issues and stuff. I haven''t actually looked at
the ConnectionPool code myself much yet.