Rails: how to get the current host, or build a URL with it?
64,829
Solution 1
I often use a before_filter
in ApplicationController
to set an instance variable with the host name, something like this:
@hostname = request.host || "www.mydomain.com"
You can also use request.port
to get the port number which the request came through (taken from the HTTP headers).
Solution 2
Basically you need to generate url based on the current url and some other port number. it can be done as -
request.url(:port => 20)
On rails console
app.root_url(:port => 20)
=> "http://www.example.com:20/"
To extract host from url use
request.host
Author by
HappyDeveloper
Updated on February 27, 2020Comments
-
HappyDeveloper about 4 years
I need to use the host to build a URL with a different port.
For example, if the host is example.com, I need to generate a URL like http://example.com:8080/
I need it to be portable, so when I'm in my local enviroment it shows http://localhost:8080/ instead.
Any ideas?