Search code examples
ruby-on-railshostnameinitializer

Rails: Get hostname in an initializer


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?


Solution

  • Use:

    `hostname`
    

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