Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 685
crishoj Avatar asked Nov 22 '12 06:11

crishoj


People also ask

How do you know on which port Rails is running?

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 .

What happens when we run Rails server?

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".

How do you stop a Rails server?

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.


3 Answers

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'
like image 125
crishoj Avatar answered Oct 10 '22 17:10

crishoj


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
like image 16
Nathan Hanna Avatar answered Oct 10 '22 19:10

Nathan Hanna


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'}}
like image 11
donV Avatar answered Oct 10 '22 19:10

donV