6

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jackson
  • 6,391
  • 6
  • 32
  • 43
  • 1
    Duplicate of [This Post](http://stackoverflow.com/questions/1610573/shutdown-hook-for-rails). P.S. `at_exit` seems correct [With a little more info](http://blog.arkency.com/2013/06/are-we-abusing-at-exit/) – engineersmnky Dec 23 '14 at 19:57
  • 1
    I would like to avoid `at_exit` because as I understand it, that can impact the exit status code. – Jackson Dec 23 '14 at 20:04

2 Answers2

8

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!" }
Community
  • 1
  • 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • This will surprisingly execute prior to a defined finalizer. – engineersmnky Dec 23 '14 at 20:20
  • As special language features, the existence of BEGIN seems less necessary than END. If you want code to run when your program starts up, you can just put the code inside a class. BEGIN is also awkward because it gets executed before any other code, so it can't call methods that you define. –  Jul 07 '21 at 15:38
3

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
engineersmnky
  • 25,495
  • 2
  • 36
  • 52