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#initialize
so 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
Returning Data from Forked Processes
How to Solve Insecure World Writable Dir /Usr in Path,Mode 040777 Warning on Ruby
How to Compile Ruby to Byte Code as with Python
Query Records Through Its Belongs_To Relation in Rails
Storing Arrays in Database Using Activerecord
How to Get Indexes of All Occurrences of a Pattern in a String
Complicated Graphviz Tree Structure
Check If a Constant Is Already Defined
Why Doesn't Ruby Have a Real Stringbuffer or Stringio
Difference Between Resource and Resources in Rails Routing
How to Add to a Serialized Array
Reading and Updating Yaml File by Ruby Code
Elasticsearch & Tire: Using Mapping and To_Indexed_JSON
How to Calculate How Many Years Passed Since a Given Date in Ruby