Ruby-on-rails Rails:如何获取当前主机,或者用它构建一个 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9452917/
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-03 02:55:01  来源:igfitidea点击:

Rails: how to get the current host, or build a URL with it?

ruby-on-railsrubyurlhost

提问by HappyDeveloper

I need to use the host to build a URL with a different port.

我需要使用主机来构建具有不同端口的 URL。

For example, if the host is example.com, I need to generate a URL like http://example.com:8080/

例如,如果主机是example.com,我需要生成一个像http://example.com:8080/这样的URL

I need it to be portable, so when I'm in my local enviroment it shows http://localhost:8080/instead.

我需要它是可移植的,所以当我在我的本地环境中时,它会显示http://localhost:8080/

Any ideas?

有任何想法吗?

回答by Alex D

I often use a before_filterin ApplicationControllerto set an instance variable with the host name, something like this:

我经常使用before_filterinApplicationController来设置一个带有主机名的实例变量,如下所示:

@hostname = request.host || "www.mydomain.com"

You can also use request.portto get the port number which the request came through (taken from the HTTP headers).

您还可以使用request.port获取请求通过的端口号(取自 HTTP 标头)。

回答by Sandip Ransing

Basically you need to generate url based on the current url and some other port number. it can be done as -

基本上,您需要根据当前 url 和其他一些端口号生成 url。它可以这样做 -

request.url(:port => 20)

On rails console

在导轨上控制台

app.root_url(:port => 20)
 => "http://www.example.com:20/" 

To extract host from url use

从 url 中提取主机使用

request.host