What is the Ruby convention for determining whether you are running in CLI (like php_sapi_name function in PHP) vs. processing an HTTP request?
I was thinking I could test if request is defined, or some other inferential method, but there must be a convention I should follow.
There’s no standardized method here since Ruby is a scripting language that may or may not be embedded in a web-server process. It may be running as a disconnected background process as well, though one that’s not necessarily web-facing.
In the HTTP environment you generally have variables defined like
ENV['SERVER_NAME']and others from the CGI specification. These would not be present in command-line environments.Generally it’s better to test if you’re running within Rack or Rails or whatever particular web framework is being employed to interface with the HTTP layer. For instance,
defined?(Rails)will indicate if Rails is loaded, though this will also be true forraketasks andrails consoletype usage.