如何确定Rails是从CLI,控制台还是作为服务器运行?

我有一个中间件,用于使用Bonjour在本地网络应用程序上宣布我的应用程序 ,但是当从rake或通过控制台调用Rails时,它也会宣布该服务。

我想排除这些情况,并且只在Rails作为服务器运行时使用Bonjour中间件。

中间件配置接受proc以使用proc在某些条件下排除中间件:

 config.middleware.insert_before ActionDispatch::Static, Rack::SSL, :exclude => proc { |env| env['HTTPS'] != 'on' } 

但是,如何确定是从CLI,控制台还是作为服务器调用Rails?

使用pry在Rails模块中查看可以检测到控制台调用,如下所示:

 Rails.const_defined? 'Console' 

和服务器调用这样:

 Rails.const_defined? 'Server' 

超级有帮助。 谢谢@crishoj。

我想更仔细地检查Console对象以解决我正在处理的另一个问题,并发现可以使用Rails::Console Console常量,因此检查的另一个选项是使用:

 defined? Rails::Console defined? Rails::Server 

当Rails 5在Passenger下运行时,未定义“服务器”。

我发现的最佳解决方案是这个答案的变体:

 if %w(rails rake).include?(File.basename($0))  else  end 

使用Rails 5有或没有像Puma / Passenger这样的app-server,这里有三种方法来确定你的应用程序的运行方式:

 # 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'}}