How can I ensure the operation is completed before Rails exits without using `at_exit`?

I have an operation that I need to perform in my rails application, which dies before my Rails application. Is there a hook I can use in Rails for this? Something similar to at_exit I think.

+5
source share
2 answers

Ruby itself supports two hooks, BEGIN and END , which are launched at the beginning of the script and how the interpreter stops running it.

See " What does BEGIN do for Ruby? For more information.

The BEGIN documentation states:

Defines, through the code block, the code that must be executed unconditionally before the sequential start of the program. Sometimes used to model direct references to methods.

 puts times_3(gets.to_i) BEGIN { def times_3(n) n * 3 end } 

The END docs say:

Indicates code that should be executed immediately before the program terminates.

 END { puts "Bye!" } 
+5
source

Well, that’s why I don’t make any guarantees regarding the impact, because I did not test it at all, but you could define your own hook, for example.

  ObjectSpace.define_finalizer(YOUR_RAILS_APP::Application, proc {puts "exiting now"}) 

Note that this will be done after at_exit , so the output of the rails application server will look like

 Stopping ... Exiting exiting now 

With Tin Man Solution Enabled

  ObjectSpace.define_finalizer(YOUR_RAILS_APP::Application, proc {puts "exiting now"}) END { puts "exiting again" } 

Exit

  Stopping ... Exiting exiting again exiting now 
+2
source

Source: https://habr.com/ru/post/1209791/


All Articles