Get hostname from Rails controller

有些话、适合烂在心里 提交于 2019-11-29 15:54:00

问题


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 it should work on both windows and linux?


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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

full_domain_path = request.env['rack.url_scheme'] + '://' + request.host_with_port


来源:https://stackoverflow.com/questions/2208835/get-hostname-from-rails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!