Rails: Get hostname in an initializer

梦想与她 提交于 2019-12-06 07:23:12

问题


I'm using Sorcery for Authentication, and I need to setup third party authentication in its initializer.

The initializer has a line that looks like this:

config.twitter.callback_url "http://example.dev/auth/callback?provider=twitter"

...where example.dev is the hostname when I'm using Pow in local development. This needs to be example.com if the app is in production, or staging.example.com if it's in staging, etc.

I would like to set this line to be something like this:

config.twitter.callback_url "#{Rails.hostname}/auth/callback?provider=twitter"

... but request.host is the only method I know of that knows that and it's only available at the controller level.

I can use a conditional test and manually setup a hostname for each environment, but as I test on different local and staging environments it would be great to just be able to set this programatically.

Any suggestions?


回答1:


Use:

`hostname`

That uses the Unix "hostname" utility, and it returns a string.




回答2:


You can get the hostname via Socket.gethostname which is part of the Ruby Standard Library.



来源:https://stackoverflow.com/questions/9764352/rails-get-hostname-in-an-initializer

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