Rails root_path in application.js

How can I get the root_path project in the application.js file?

I need this for a js plugin ( codemirror ) that needs to load other JS files. All this is fine and dandy if I say / javascripts/needed_file.js, but what if I split my project into / custom.

The code should do its magic throughout the project, and I would like it to be UJS, so it should be in a static javascript file.

Any solutions / simple hacks?

+6
javascript ruby-on-rails codemirror
source share
3 answers

There is no beautiful solution. I would try one of the following methods:

  • Inspect window.location.pathname . Determine if it works from the root or from the prefix URL.

  • Add something like <script type="text/javascript" charset="utf-8">var ROOT_PATH = '<%= Rails.root_path %>';</script> somewhere at the top of your layout file.

  • Use this pretty hacky function (I suspect it might break with some HTML5 script attributes):

     function urlOfCurrentFile() { var scripts = document.getElementsByTagName("script"); return scripts[scripts.length - 1].src; } 
+6
source share

I have this in my header file.

 <script type="text/javascript"> var BASE_URL = '<%= root_url %>'; </script> 
+1
source share

Ok, the best way to find a way to use JS for this, for example:

 window.location.origin # http://localhost:3000/ 

It will give you the fully qualified host name, with http:// and port number. As with starting a local Rails server, it will give you: http://localhost:3000

 window.location.hostname # localhost 

It will just give you the host name and nothing about the port or HTTP. Enabling a Rails server working locally will give you: localhost .

0
source share