1

This is the code for the jplayer:

songs/show.html.erb

<% content_for :mp3script do %>
    <script type="text/javascript">
    //<![CDATA[
    $(document).ready(function(){

      $("#jquery_jplayer_1").jPlayer({
        ready: function () {
          $(this).jPlayer("setMedia", {
            mp3: "<%= @song.mp3.url %>"
          }).jPlayer("play");
        },
      });
    });
    //]]>
    </script>
<% end %>

I have this on the head of application.html.erb:

 <%= yield :mp3script %>

Everything works fine, but it's a bit ugly to put the JavaScript inside html directly, so I want to put it in a .js.erb file.

When I put it in mp3script.js.erb it give this error:

undefined method `mp3' for nil:NilClass

If I succeed in putting the javascript in a .js.erb is the javascript application.js going to be re-compiled every time the mp3 link change in production? I think this is bad, right?

user229044
  • 232,980
  • 40
  • 330
  • 338
anouar
  • 125
  • 1
  • 1
  • 10

1 Answers1

1

You can't push data from controllers into the asset pipeline, the asset pipeline has no access to your controller's instance variables or even the current request object, as they will not exist when the assets are precompiled.

Your current approach is correct.

is the javascript application.js going to be re-compiled every time the mp3 link change in production?

No, that isn't how the asset pipeline works, and it's precisely the reason you can't move your dynamically generated JavaScript into a .js.erb file.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • so there is no solution , i just think it not good the expose the mp3 url in the html like that – anouar Mar 08 '16 at 13:00
  • @anouar you'd still be exposing it in the JavaScript, what's the difference? – user229044 Mar 08 '16 at 13:01
  • do you have any solution ? so the mp3 url not shown directly on the html , any one hit the ctrl + u is gonna see it – anouar Mar 08 '16 at 13:02
  • @anouar no, that's impossible. No matter what you do, the user can easily see the URL. – user229044 Mar 08 '16 at 13:02
  • ok thanks , i think i will put the mp3 url behind a controller at least that way the user cant know the exact location on the server – anouar Mar 08 '16 at 13:05