26

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?

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.

AMIC MING
  • 6,306
  • 6
  • 46
  • 62
alex
  • 1,900
  • 3
  • 24
  • 34

3 Answers3

50

You have several options:

  • call system's hostname command (assuming it's *nix): `hostname`
  • use the socket gem:

    require 'socket'

    Socket.gethostname

  • in case you just want to know the current domain the request visits: request.domain

Update

From the request object, we can fetch both the host and the port, please check out these methods:

  • request.protocol
  • request.host
  • request.port

You could build the full url from these methods.

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.

Marius Butuc
  • 17,781
  • 22
  • 77
  • 111
James Chen
  • 10,794
  • 1
  • 41
  • 38
  • James, thanks for your answer, but I think I didn't phrase my question properly. I made a quick edit. I tried your easy solution on my local machine and it returns my machine's name while I'd like to get 'localhost:3000'... – alex Aug 23 '11 at 00:59
  • 1
    Can i call this methods from a Model? It gives me an error undefined method request – inquisitive Jan 30 '15 at 05:26
  • @Inquisitive Only controller has access to `request`. It's a bad idea to let model have knowledge of request. – James Chen Jan 30 '15 at 07:29
25

Use the following method on ActionController:

request.host_with_port
IAmNaN
  • 10,305
  • 3
  • 53
  • 51
19

It’s actually easy. The best suggestion I have for solving this problem is that you create a before_filter that sets it on each request in ApplicationController.rb like so:

 before_filter :set_mailer_host

  def set_mailer_host
    ActionMailer::Base.default_url_options[:host] = request.host_with_port
  end
jimagic
  • 4,045
  • 2
  • 28
  • 49