I have built a pretty simple REST service in Sinatra, on Rack. It\'s backed by 3 Tokyo Cabinet/Table datastores, which have connections that need to be opened and closed. I
If you have other Rack middleware that depend on these connections (by way of a dependence on your model classes), then I wouldn't put the connection logic in Sinatra -- what happens if you rip out Sinatra and put in another endpoint?
Since you want connection-per-application rather than connection-per-request, you could easily write a middleware that initialized and cleaned up connections (sort of the Guard Idiom as applied to Rack) and install it ahead of any other middleware that need the connections.
class TokyoCabinetConnectionManagerMiddleware
class < e
puts "Error closing Tokyo Cabinet connection. You might have to clean up manually."
end
end
end
end
If you later decide you want connection-per-thread or connection-per-request, you can change this middleware to put the connection in the env Hash
, but you'll need to change your models as well. Perhaps this middleware could set a connection
variable in each model class instead of storing it internally? In that case, you might want to do more checking about the state of the connection in the at_exit
hook because another thread/request might have closed it.