0
votes

I have an extremely unusual case where I need to connect to a sqlite database using an anonymous class. This class in created on every request, and then connects to a database using ActiveRecord's establish_connection. My issue is that every time establish_connection is called, ActiveRecord creates a new connection pool to track the connections made through the class. Since these are one time use classes, this is actually a memory leak and the number of connection pools tracked by ActiveRecord grows with each request. One way to solve this is to call

model_copy = Class.new Model { ... }
model_copy.establish_connection ...
# Do work
model_copy.connection.disconnect!
model_copy.connection_handler.remove_connection model_copy

I would like to do this without the explicit disconnect! and remove_connection calls because it is annoying and very prone to errors and memory leaks. Does anyone have any guidance here?

Thanks!

1

1 Answers

1
votes

Assuming the # Do work part is the only part that changes, this looks like a classic use case for a method that takes a block:

def hit_the_db
  model_copy = Class.new Model { ... }
  model_copy.establish_connection ...
  yield
  model_copy.connection.disconnect!
  model_copy.connection_handler.remove_connection model_copy
end

...

hit_the_db { block of code that does work }