0

I have the following script in show.html.erb page, in order to update my progress bar. However it uses jQuery, and since jQuery is just loaded at the end of my application.html.erb layout, I cannot use it on my page. So I am requiring it also on my show.html.erb page before the script code.

It's clear that this is not the right way to do it. Where should I put my script code so as it's just loaded for this page? Another problem is that it uses information from the controller (@batch). If I move it to a js file in my assets folder, how can I access it?

The following code is placed at the end of show.html.erb

<%= javascript_include_tag "application" %>

<script type="text/javascript">
function progress(){
    var progress = setInterval(function() {
      var $bar = $('.bar');
      var $pct = $('#pct');
      $.get("<%= @batch.id %>/status.json", function(data){
        if (data.status == "done") {
          location.reload();
        } else {
          $bar.width(data.progress+"%");
          $pct.text(data.progress+"%");
        }
      });
    }, 800);
}

$(document).ready(function() {
  $.get("<%= @batch.id %>/status.json", function(data) {
    if (data.status == "processing") {
      progress();
    }
  });
});
</script>

EDIT

Since now I'm getting batch_id, I can check if it exists to run the code:

$(document).ready(function() {
  var batch_id = $("#batch").data("batch-id");
  if (batch_id != null) {
    $.get(batch_id + "/status.json", function(data) {
      if (data.status == "processing") {
        progress();
      }
    });
  }
});

1 Answer 1

1

The way to handle this is by unobtrusive javascript (separate your javascript from html).

First, move the <%= javascript_include_tag "application" %> in the <head> section of the application.html.erb file, so that it properly loads jquery on each page.

Then, move your script inside a js file in your assets directory.

To access the @batch.id, add this id inside a data attribute, in your view file (show.html.erb).

<div id="etc" data-batch-id="<%= @batch.id %>"></div>

Then, inside your script:

var batch_id = $("#etc").data("batch-id")
$.get(batch_id + "/status.json", ...
Sign up to request clarification or add additional context in comments.

2 Comments

Is it Ok for that code to run on every page, even if there is no progress bar? Or should I restrict it to my show view? If I should restrict it, how can I do it? :)
yes, that should do it. Regarding loading jquery just for this individual page...I don't know what's the best practice to do this. Perhaps it's worth another question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.