alexcepoi alexcepoi - 1 year ago 110
Javascript Question

Rails root_path in application.js

How can I get my hands on the project's

in my application.js file?

I need it for a js plugin (codemirror) that needs to load other JS files. It's all fine and dandy if I say "/javascripts/needed_file.js", but what if I deploy my project to "/custom".

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

Any solutions/simple hacks?

Answer Source

There's no beautiful solution. I'd try one of these approaches:

  • Inspect window.location.pathname. Determine from this whether running from root or from a prefix url.

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

  • Use this quite hackish function (I suspect that it might break with some of the HTML5 script attributes):

    function urlOfCurrentFile() {
      var scripts = document.getElementsByTagName("script");
      return scripts[scripts.length - 1].src;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download