9

I need to perform certain initialization depending on web server that is used to start the application. Is it possible to detect it programmatically from rails initializer?

Stas S
  • 1,022
  • 1
  • 8
  • 18
  • 3
    Why do you need to know that, what kind of initialization depends on the type of the web server? Tell us more about what you want to achieve, perhaps there is a better way. It sounds weird to me that an application should be responseable for finding out such information. I think it is a better idea to pass that information to the app (via ENV for example). – spickermann May 23 '14 at 14:43
  • Yeah, I know it's a bit weird... And I'm afraid that it will be more weird if I go into details. But... There are child processes that started from our rails app (we use selenium webdriver for making server side screenshots, that runs firefox child process). The problem is that thin doesn't kill these processes on stop/restart, but Passenger does. So I'd like to close firefox manually only when the app is running under thin. Though I don't know yet how to catch 'exit event' because `at_exit` handler is not called on restarts, only on stop. – Stas S May 23 '14 at 15:14
  • Actually, I need a guarantied way to close all child processes of rails app when it is stopped/restarted, not depending on particular web server, but it is, probably, another question. – Stas S May 23 '14 at 15:28

3 Answers3

0

Even though it's not that clean, you can use

defined?(::Thin) 
defined?(::Unicorn)
defined?(::Passanger)

and so on. This will work for these three, and you have to check if it works with others.

roman-roman
  • 2,746
  • 19
  • 27
0

You can check whether the process is running or not using ps aux

ps aux | grep passenger
ps aux | grep puma
ps aux | grep unicorm
Aniket Tiwari
  • 3,561
  • 4
  • 21
  • 61
  • The OP asked `detect it programmatically from rails initializer` that means from Ruby code. Now you could still run a system command but still you would not get the desired result – Cyril Duchon-Doris Jul 18 '19 at 13:21
  • @CyrilDuchon-Doris What desired result we won't get when running the above commands? – Aniket Tiwari Aug 02 '19 at 07:26
  • Although you could run those as system commands, if you have several processes opened (ie several passenger processes running) this won't help you detect whether the *current* app is ran using a webserver or not. – Cyril Duchon-Doris Aug 02 '19 at 12:15
-1

Here's a kind of hacky way to do it (in config/application.rb add):

module Rails
  class Server < ::Rack::Server
    alias_method :old_start, :start
    def start
      puts server.name # or set an ENV variable
      old_start
    end
  end
end
Jacob Brown
  • 7,221
  • 4
  • 30
  • 50
  • Unfortunately, it doesn't work if the server is started not via `rails server` command. In my case thin is started via `thin start` and Passenger is a nginx module. – Stas S May 23 '14 at 20:49