0

Currently I do something like this:

+    var go_to = "http://localhost:3000" + url; 
+    window.open(go_to);

Which takes it to the Index action of a Rail controller and eventually shows the page.

Two things I want to improve: 1- Definitely hard coding "http://localhost:3000" is dead wrong. But what is the right way?

2- Is there a better way of talking to Rails from JS side to open a new window?

  • 1
    Use `window.location` (http://www.w3schools.com/js/js_window_location.asp): 1): You can use `window.location.hostname` to get the hostname. 2): I don't think there is better solution that `window.open(url)` (http://stackoverflow.com/questions/7077770/window-location-href-and-window-open-methods-in-javascript) – MrYoshiji Aug 15 '13 at 19:34
  • Ok tried window.location.hostname , it gives me like "localhost" but notice I still have that port number there? Is there a way to totally autogenerate that hard coded part of "http://localhost:3000" –  Aug 15 '13 at 19:41
  • 1
    `window.location.hostname + ':' + window.location.port` should solve the problem of the port (don't add it if equal to 80). I don't think there is a way to autogenerate the url. But the URL you are describing looks like the development mode. You could try something like (sorry for inline code): `if(window.location.hostname.indexOf('localhost') > -1){var url = "localhost:3000"} else { var url = window.location.hostname;}` – MrYoshiji Aug 15 '13 at 19:46
  • Ah I agree about the development more. Good call. –  Aug 15 '13 at 19:47

1 Answers1

1

To go to the web root, use:

    window.location = '/';

You can also do that for any other page, such as:

    window.location = '/about/';

Starting your destination with '/' will change the page within your site / current domain. So locally it'll be localhost:3000/ but when live on a server, it will go to http://www.mydomain.com/

Also if you're looking for a better way to talk to rails urls from your application, you can use the routes variables. In your console run rake routes and it'll list all the routes you have. So the variable root_path will return / or whatever your root path may be set to within your app.

    <%= link_to "Home", root_path, target: '_blank' %>
Michael Lynch
  • 1,743
  • 15
  • 27