Detect base url in controller?

Viewed 534

How can we detect the root / base url in the controller?

I'm running a function that needs to know where to return the user to after it's finished, and I would like it to work in dev and prod. Presently, if I simply use the domain name, then in development it returns the user to the actual website (i.e. www.example.com/reauth, rather than http://localhost:3000), which isn't desirable (in dev, the user should be returned to dev; they shouldn't be linked to the prod version of the site).

So I want code that returns:

  • https://www.example.com in production and
  • http://localhost:3000 in development

Example

Here's a simplified version of the exact example I need the value for refresh_url set to:

  • https://www.example.com/reauth in production and,
  • localhost:3000/reauth in development

Note the critical thing here is that the latter part of the url is the same, but the first part (base url) is the actual domain in production, and localhost in development.

Stripe::AccountLink.create({
    refresh_url: 'https://www.example.com/reauth'
  })

What I know so far

I've looked at:

1 Answers

I worked out that the method here works.

i.e.

request.base_url

Notes:

  • this will return the url without a trailing forward slash.
  • this won't work in the rails console

For future reference, here's what solved for me to give the correct base url depending on whether the app's being run in dev or prod:

base_url = (!Rails.const_defined? 'Console') ? (request.base_url) : "http://localhost:3000"
Related