如何确定 Rails 是从 CLI、控制台还是作为服务器运行? [英] How to determine if Rails is running from CLI, console or as server?

查看:41
本文介绍了如何确定 Rails 是从 CLI、控制台还是作为服务器运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I'd like to exclude these cases, and only use the Bonjour middleware when Rails is running as a server.

中间件配置接受一个 proc 以在特定条件下使用 proc 排除中间件:

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

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

But how do I determine if Rails was invoked from the CLI, console or as a server?

推荐答案

使用pry查看Rails模块 表明可以像这样检测控制台调用:

Peeking at the Rails module using pry reveals that console invocations can be detected like this:

Rails.const_defined? 'Console'

像这样的服务器调用:

Rails.const_defined? 'Server'

这篇关于如何确定 Rails 是从 CLI、控制台还是作为服务器运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆