0

I am facing an issue with the host name in rails 3.

I need to access host in `config/initializers/file.rb but without socket gem and any gem.

host like app url

www.app.com

Could you please let me know that how it would be possible for me.

Thanks in advance.

ROR
  • 441
  • 2
  • 13

2 Answers2

2

Since you can't get a hold of a request object in an initializer, you'll need to use socket from the standard library. Socket is not gem, so no gem installation is necessary!

Et viola:

require 'socket'
Socket.gethostname

This assumes though that host name of your device matches the address you seek (run the command hostname in the terminal to see what I mean). If that's not the case, you won't be able to determine the host name until a request is made, since any number of addresses can point to the same application. It might be wiser to set this through configuration variables.

If you really want something dynamic, the closest you can get is by performing the initializer within a controller. Here's an example that will dynamically set action_mailer.default_url_options based on the first request made to the server.

class ApplicationController < ActionController::Base
  before_action :set_mailer_host

  private

  def set_mailer_host
    if !ProMetrics::Application.config.action_mailer.default_url_options
      ProMetrics::Application.config.action_mailer.default_url_options = { host: request.host, port: request.port }
    end
  end
end
fny
  • 31,255
  • 16
  • 96
  • 127
  • Socket.gethostname return "rails" in config/initializers/file.rb so it is not working for me. thanks – ROR Apr 17 '15 at 06:43
  • 1
    That's the actual hostname of the computer (i.e. same result as typing `hostname` in bash). You're not going to be able to determine a host name until you make a request since any number of addresses can point to the same host. You should consider moving this configuration step into a controller. – fny Apr 17 '15 at 10:43
2

Perhaps just a simple system call:

`hostname`.chomp
spickermann
  • 100,941
  • 9
  • 101
  • 131