Detect If Application Was Started as Http Server or Not (Rake Task, Rconsole etc)

Detect if application was started as HTTP server or not (rake task, rconsole etc)

There's not a great way of doing this that I know of. You could copy newrelic's approach (check discover_dispatcher in local_environment.rb) which basically has a list of heuristics used to detect if it is running inside passenger, thin, etc.

For passenger it checks

defined?(::PhusionPassenger)

for thin it checks

if defined?(::Thin) && defined?(::Thin::Server)

Detect if application was started as HTTP server or not (rake task, rconsole etc)

There's not a great way of doing this that I know of. You could copy newrelic's approach (check discover_dispatcher in local_environment.rb) which basically has a list of heuristics used to detect if it is running inside passenger, thin, etc.

For passenger it checks

defined?(::PhusionPassenger)

for thin it checks

if defined?(::Thin) && defined?(::Thin::Server)

How to determine if Rails is running from CLI, console or as server?

Peeking at the Rails module using pry reveals that console invocations can be detected like this:

Rails.const_defined? 'Console'

And server invocations like this:

Rails.const_defined? 'Server'

Rails: How to run code when server starts up, but not when running a rake task or the console?

What web server are you using? On Puma, for example, you can use

on_worker_boot do
# Establish RabbitMQ connection
end

Another possibility might be to check if defined?(Rails::Server) in your initializer: this should only be true when running in the context of the web server.

how to detect if you are running outside of the rails main app

To check if the server is active use:

Rails.const_defined? 'Server'

Rails 3 initializers that run only on `rails server` and not `rails generate`, etc

Can you do something like overriding Rails::Server#initializeso that it invokes your initialization code in your initializer?

Or, more easily, just put your code in script/rails, as that will be run everytime you run rails server, you can easily fiddle with ARGV or ENV in there.



Related Topics



Leave a reply



Submit