Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure an operation runs before Rails exits, without using `at_exit`?

I have an operation that I need to execute in my rails application that before my Rails app dies. Is there a hook I can utilize in Rails for this? Something similar to at_exit I guess.

like image 346
Jackson Avatar asked Dec 23 '14 19:12

Jackson


2 Answers

Ruby itself supports two hooks, BEGIN and END, which are run at the start of a script and as the interpreter stops running it.

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

The BEGIN documentation says:

Designates, via code block, code to be executed unconditionally before sequential execution of the program begins. Sometimes used to simulate forward references to methods.

puts times_3(gets.to_i)

BEGIN {
  def times_3(n)
    n * 3
  end
}

The END documentations says:

Designates, via code block, code to be executed just prior to program termination.

END { puts "Bye!" }
like image 62
the Tin Man Avatar answered Nov 03 '22 19:11

the Tin Man


Okay so I am making no guarantees as to impact because I have not tested this at all but you could define your own hook e.g.

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

Note this will execute after at_exit so the rails application server output will look like

Stopping ...
Exiting
exiting now

With Tin Man's solution included

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

Output is

 Stopping ...
 Exiting
 exiting again
 exiting now
like image 3
engineersmnky Avatar answered Nov 03 '22 20:11

engineersmnky