views:

79

answers:

2

In Rails, in an initializer/environment.rb Whats the pefered way to detemrine if the webapp itself is being loaded (script/server).

All the initializers are loaded for migrations script/console and other rails task as well, but in my case some stuff only has to be loaded when the server itself is being initialized.

My ideas: checking $0

Thanks! Reto

A: 

There is probably a better way to do this, but since I am not aware of one, I would probably alter script/server to set an environment variable of some kind.

Then I would have my initializer check for that environment variable.

hernan43
+3  A: 

Because there are multiple application servers, each with their own initialization strategy, I would recommend the only way to reliably hook into the server boot process: ActionController::Dispatcher.

The dispatcher has some callbacks; namely:

  • prepare_dispatch (added with to_prepare)
  • before_dispatch
  • after_dispatch

The "prepare" callbacks are run before every request in development mode, and before the first request in production mode. The Rails configuration object allows you to add such callbacks via its own to_prepare method:

Rails::Initializer.run do |config|
  config.to_prepare do
    # do your special initialization stuff
  end
end

Unfortunately, to my knowledge this callback will always be run since Rails initializer calls Dispatcher.run_prepare_callbacks regardless of if we're booting up with a server or to a script/console or even a rake task. You want to avoid this, so you might try this in your environment.rb:

Rails::Initializer.run do |config|
  # your normal stuff
end

if defined? ActionController::Dispatcher
  ActionController::Dispatcher.to_prepare do
    # your special stuff
  end
end

Now, your "special stuff" will only execute before first request in production mode, but before every request in development. If you're loading extra libraries, you might want to avoid loading something twice by putting an if statement around load or require. The require method will not load a single file twice, but I still recommend that you put a guard around it.

mislav
Thanks! Checking for the dispatcher sounds like a very good idea! But I won't hook into 'to_prepare' as I only need to do some things once (at startup). But the concept remains the same! Great :D.
reto
ah I see, no, ActionController::Dispatcher is defined in any case. It might be caused by the fact that I'm using jruby. Dunno. I think I will fall back to $0 for now. Thanks anyway!
reto
Nevermind! It works perfectly, silly me placed a 'puts "dispatched loaded"' at the wrong position ;). thanks
reto