问题描述
在 Rails 2.3 中,我可以只使用 HOST 来获取我的主机名,但它似乎不再可用.我可以用什么代替?
In Rails 2.3, I could just use HOST to get my hostname but it seems it's not available anymore. What can I use instead?
我只想要在我的机器上运行代码时返回 localhost:xxxx
(带有真实端口号)的东西,以及 http://www.mysite.com
在生产环境中运行时.
I just want something that returns localhost:xxxx
(with real port number) when I run the code from my machine, and http://www.mysite.com
when I run it in production.
推荐答案
您有几个选择:
- 调用系统的主机名命令(假设它是*nix):
`hostname
` 使用插槽宝石:
- call system's hostname command (assuming it's *nix):
`hostname
` use the socket gem:
需要'socket'
Socket.gethostname
如果您只想知道请求访问的当前域:request.domain
in case you just want to know the current domain the request visits: request.domain
更新
从请求对象中,我们可以获取主机和端口,请查看以下方法:
From the request object, we can fetch both the host and the port, please check out these methods:
request.protocol
request.host
request.port
您可以通过这些方法构建完整的 url.
You could build the full url from these methods.
根据我的个人经验,对于大多数项目,您可能为每个环境都有一个固定的域,并且通常在 yaml 文件左右配置它(例如,要发送电子邮件并在电子邮件正文中使用带有域名的 url,我们通常阅读配置并为 url 助手设置选项).所以我通常只是读取当前环境的 urls 配置并从代码中使用它们.
From my personal experience, for most projects you might have a fixed domain for each environment, and usually configure that in a yaml file or so (for example, to send email and use urls with domain name in the email body, we usually read the config and set options for url helper). So I usually just read the current environment's urls configuration and use them from the code.
这篇关于如何在 Rails 3 中获取主机名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!