2

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:

stevec
  • 15,490
  • 6
  • 67
  • 110
  • I have simplified this as much as possible, while providing as much detail as required for the question to be fully understandable. I hope it can be reopened – stevec Nov 06 '20 at 19:21
  • Consider seeing a `root` url or seeing up a new route with a named helper. Unless example.com is not your server, you shouldn't need to use `.base_url` – BKSpurgeon Nov 06 '20 at 19:30

1 Answers1

0

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"
stevec
  • 15,490
  • 6
  • 67
  • 110
  • 2
    It won't work in console because the request object is only available in controllers. – MibraDev Oct 12 '20 at 18:33
  • @MibraDev thanks for letting me know. Is that because the request object is generated on the app booting up or for some other reason? Is there a sensible pattern for testing objects that don't exist in the rails console (rails console is my 'go to' for testing code, so this problem took longer than it should have to solve since I couldn't get `request.base_url` to work in the console). Really appreciate any advice – stevec Oct 12 '20 at 18:36
  • 3
    @stevec The request object is a representation of the current HTTP request. There is no current HTTP request in the console. You will only have one in the context of a controller action (or the router, a middleware class, maybe a few other rare cases). You can use a debugger like byebug to get an interactive console environment in the middle of some controller code and then test there. – danthedaniel Oct 12 '20 at 20:39