I have a middleware for announcing my application on the local network app using Bonjour, but it's also announcing the service when Rails is invoked from rake or through the console.
I'd like to exclude these cases, and only use the Bonjour middleware when Rails is running as a server.
The middleware configuration accepts a proc to exclude middlewares under certain conditions using a proc
:
config.middleware.insert_before ActionDispatch::Static, Rack::SSL, :exclude => proc { |env|
env['HTTPS'] != 'on'
}
But how do I determine if Rails was invoked from the CLI, console or as a server?
You can call Rails::Server. new. options[:Port] to get the port that your Rails server is running on. This will parse the -p 3001 args from your rails server command, or default to port 3000 .
One of the things rails server does is that it loads all the dependencies/gems required by your Rails app, or at least sets them up to be auto-loaded later when they are needed. This is sometimes called "booting" or loading the "Rails environment".
For Rails 5.0 and above, you can use this command Use ctrl+c to shutdown your Webrick Server. Unfortunately if its not works then forcefully close the terminal and restart it.
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'
Super helpful. Thanks @crishoj.
I wanted to examine the Console object more closely for another problem I am working on and found out that the Console constant can be reached with Rails::Console
, so another option for checking would be to use:
defined? Rails::Console
defined? Rails::Server
Using Rails 5 with or without an app-server like Puma/Passenger, here are three ways to determine how your app is running:
# We are running in a CLI console
defined?(Rails::Console)
# We are running as a Rack application (including Rails)
caller.any?{|l| l =~ %r{/config.ru/}}
# We are running as a CLI console
caller.any?{|l| l =~ %r{/lib/rake/task.rb:\d+:in `execute'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With