Get hostname from Rails controller

前端 未结 4 437
一整个雨季
一整个雨季 2021-01-01 08:23

I am trying to get the hostname of the machine which a rails application is running on from the controller.

What would be the best way to do this taking into account

相关标签:
4条回答
  • 2021-01-01 09:07

    If you need the full domain path from protocol to port, try:

    full_domain_path = request.env['rack.url_scheme'] + '://' + request.host_with_port
    
    0 讨论(0)
  • 2021-01-01 09:20

    All you have to do is look at the request object in your controller:

    request.host_with_port
    

    or if you don't want the port, just

    request.host
    
    0 讨论(0)
  • 2021-01-01 09:23

    There's always:

    require 'socket'
    ...
    Socket.gethostname
    

    I've got no Windows box handy with which to test this, but the docs make no mention of it being *nix specific.

    Note: The require statement is not necessary for Rails 4, and probably other Rails versions as well. It is required if you are doing plain Ruby without Rails.

    0 讨论(0)
  • 2021-01-01 09:27

    Use backticks and the command hostname

    current_host = `hostname`
    

    This sends the command to the shell, and returns the hostname. Works on at least: Debian Linux, Windows, Solaris.

    0 讨论(0)
提交回复
热议问题