Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails root_path in application.js

How can I get my hands on the project's root_path 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?

like image 754
alexcepoi Avatar asked Jan 24 '11 21:01

alexcepoi


2 Answers

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;
    }
    
like image 134
Jakub Hampl Avatar answered Sep 28 '22 03:09

Jakub Hampl


I have this in my header file.

<script type="text/javascript">
  var BASE_URL = '<%= root_url %>';
</script>
like image 41
Kenny Cason Avatar answered Sep 28 '22 03:09

Kenny Cason