How to pass a parameter to a singleton definition?

I’m new to Ruby and this is my first (silly) question. Hope not too much

I’d like to create a function that, when certain connections to
Postgresql are closed, it automatically executes some clean up code.

The idea was that you can customise the clean up code, so that you can
pass a code block to each connection and state the actions to perform.

So I come up with this code:
def self.on_db_close(pg_connection, &block)
class << pg_connection
alias old_close close
alias old_finish finish
@__on_db_close_callback = block;

def close(*args)

# I was expecting that finish() was implemented on top of close() or

anyway the other way around, but it isn’t, at least at the ruby level
def finish(*args)

and then you’d invoke the function with:
c = PG::connect( … )
on_db_close© { __hook_log_close; }

Unfortunately my diabolic plan is currently beaten by this error that is
raised when trying the above snippet of code:

./database.rb:65:in singleton class': undefined local variable or methodblock’ for #<Class:#PG::Connection:0x0000000241ee78>
from ./database.rb:61:in `on_db_close’

So apparently I’m not correctly creating the closure with the custom
block. What’s the proper solution for this case?

Many thanks in advance.

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