Ruby-on-rails 从 Rails 控制器获取主机名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2208835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:15:20  来源:igfitidea点击:

Get hostname from Rails controller

ruby-on-railshostname

提问by RailsSon

I am trying to get the hostname of the machine which a rails application is running on from the controller.

我正在尝试从控制器获取运行 rails 应用程序的机器的主机名。

What would be the best way to do this taking into account it should work on both windows and linux?

考虑到它应该在 windows 和 linux 上都可以使用,最好的方法是什么?

采纳答案by Wayne Conrad

There's always:

总有:

require 'socket'
...
Socket.gethostname

I've got no Windows box handy with which to test this, but the docs make no mention of it being *nix specific.

我没有方便的 Windows 盒子来测试这个,但是文档没有提到它是 *nix 特定的。

Note: The require statement is not necessary for Rails 4, and probably other Rails versions as well. It is required if you are doing plain Ruby without Rails.

注意: require 语句对于 Rails 4 不是必需的,其他 Rails 版本也可能如此。如果你在做没有 Rails 的普通 Ruby,它是必需的。

回答by Wilhelm

All you have to do is look at the request object in your controller:

您所要做的就是查看控制器中的请求对象:

request.host_with_port

or if you don't want the port, just

或者,如果您不想要端口,只需

request.host

回答by btelles

Use backticks and the command hostname

使用反引号和命令 hostname

current_host = `hostname`

This sends the command to the shell, and returns the hostname. Works on at least: Debian Linux, Windows, Solaris.

这会将命令发送到 shell,并返回主机名。至少适用于:Debian Linux、Windows、Solaris。

回答by webaholik

If you need the full domain path from protocol to port, try:

如果您需要从协议到端口的完整域路径,请尝试:

full_domain_path = request.env['rack.url_scheme'] + '://' + request.host_with_port