29

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?

HappyDeveloper
  • 12,480
  • 22
  • 82
  • 117

2 Answers2

50

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).

Alex D
  • 29,755
  • 7
  • 80
  • 126
13

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
Sandip Ransing
  • 7,583
  • 4
  • 37
  • 48