Tracking progress in a Rails job using Coffeescript

Recently, I came across a helpful gem called this gem, which allows for the seamless integration of bootstrap progress bars and the delayed job gem. The example provided by the creator uses .haml files, but since my project utilizes erb and coffeescript, I attempted to replicate his approach.

Here is a snippet from my controller:

def export
    @job = Delayed::Job.enqueue StandingsJob.new
end

This is what I have in the routes.rb file:

get 'export', to: 'scraper#export'

And this is how my home.erb.html looks like:

<%= link_to 'export', export_path, {id:'mario', remote: true} %>

<div class="progress">
  <div class="progress-bar progress-bar-striped active" role="progressbar"
       aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
    0%
  </div>
</div>

Additionally, here's a snippet from my coffeescript file:

$(document).on "turbolinks:load", ->
    $('#mario').on 'click', ->
      alert('hocliccatoooo')
      interval = setInterval( ->
        $.ajax(
          url: '/progress-job/' **** What should I add here?????****,
          success: (job) ->
            console.log('loool')
            stage
            progress
            if job.last_error != null
              $('.progress-status').addClass('text-danger').text(job.progress_stage);
              $('.progress-bar').addClass('progress-bar-danger');
              $('.progress').removeClass('active');
              clearInterval(interval);

            if job.progress_stage != null
                stage = job.progress_stage
                progress = job.progress_current / job.progress_max * 100
            else
              progress = 0
              stage = 'Uploading file?'

            if progress != 0
              $('.progress-bar').css('width', progress + '%').text(progress + '%')
            $('.progress-status').text(stage);
          error: ->
            alert('errore')
            $('.progress').removeClass('active');
            $('.progress-bar').css('width', '100%').text('100%');
            $('.progress-status').text('Finito!!!');
            clearInterval(interval);

        )
      , 100)

While the code functions correctly upon clicking the link, I'm facing an issue figuring out how to pass the ID of the job created in the controller action to the coffeescript file. Any suggestions would be greatly appreciated!

[EDIT]

This is what I have in the job class:

class StandingsJob < ProgressJob::Base

  def perform
    update_stage 'Faccio cose'
    update_progress_max 10
    for i in [0..10]
      sleep(2)
      update_progress
    end
  end
end

Upon further investigation, it appears that the perform method of my job is not being triggered (I added a puts 'lol' statement but never saw the output in the console).

Answer №1

interval = setInterval( -> var paramJob = '<%[email protected]_json%>'; // retrieving @job parameter ->

//replace SYM with "&" + "quot;" in the string

var jobObj = JSON.parse(('{' + paramJob.slice(paramJob.indexOf("SYMid"), paramJob.length)).replace(/SYM/g, '"'));//Processing the parameters

//in the ajax use jobObj.id url: '/progress-job/' + jobObj.id,

hope this explanation aids you!

Answer №2

The issue at hand here is the difference between client side and server side processing.

To resolve this, you need to assign the job-id to a data-attribute within the HTML tag during the server side rendering process. This data should be stored in the @job variable within your controller action.

After the page has been rendered and you have transitioned to the client side coffeescript code, you can extract and utilize this attribute as needed. Here is information on how to accomplish this task.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to initialize events based on a variable

This particular plugin is structured in the following way: (function($){ var defaults = { param1:null, param2:null }; var methods = { init:function(params) { var ...

What's preventing me from utilizing Leaflet Map on Next.js despite attempting Dynamic Import?

When using Leaflet, it requires the global window object which is not available on SSR (Server-Side Rendering) and can cause an error stating "window is not defined". I have tried extensively to find a solution, and the only method I found was to use dyna ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

The Google Apps Script will activate only on weekdays between the hours of 10 AM and 5 PM, running every hour

function Purchase() { var ss=SpreadsheetApp.getActive(); var sheet=ss.getSheetByName("Buy"); var Cvalues=sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues(); var Avalues=sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues(); var r ...

pause in execution between iterations of a for loop

Challenge I'm currently working on a function that processes a list of strings by printing each one on a new line, with CSS animations that gradually display the string over a few seconds. However, I'm struggling to make sure that the next strin ...

Utilizing a StyledComponents theme within a Component

When creating a style called Link, the theme is contained inside of this.props. How can the theme be extracted from props and passed into the Link styled component? Error: ReferenceError - theme is not defined import React from 'react'; impo ...

Encountering a Type Error in React Native when attempting to create a 3D cube with Three.js

Following a tutorial on creating a simple app that displays a 3D cube, I encountered an issue with my code: import React from 'react' import {View} from 'react-native' import Expo from 'expo' import {Scene, Mesh, MeshBasicMate ...

Delete the placeholder image from a div once live content has been inserted into it

If I have a container div that displays an image when empty, but I want to remove the image when content is dynamically added to the container, what would be the most effective way to do this with jQuery? The usual method of checking if the container' ...

combine multiple keys into a single element with angular-translate

Within my application, I am retrieving translation keys from a single cell within a database table and dynamically displaying them on a settings page. While most entries will have just one key in the display object, there are some that contain multiple key ...

Retrieving an Element that Triggered an HTTP GET Request in Node.js with Express

In my Express front-end development project, I have a table with rows containing links that trigger GET requests. These requests are sent to the back-end, which is created using node.js, in order to retrieve files corresponding to each row. All links follo ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

One way to eliminate a prefix from a downloaded file path is by trimming the URL. For example, if you have a URL like "http://localhost

As my web app runs on port number, I am looking to download some files in a specific section. However, the download file path is being prefixed with "". <a href={file_path} download={file_name}> <Button variant={"link"}> <b>Dow ...

Convert the jade file to an HTML file while keeping the original file name

I'm currently attempting to configure Jade in a way that allows me to save my Jade files as HTML files while retaining the same file name. For example, I would like the file views/index.jade to be saved as dist/index.html This should apply to all ad ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

What methods can be used to block direct attribute updates in a JS/TS class?

class Creature { secretProperty modifySecretProperty(value) { this.secretProperty = value } } new Creature().modifySecretProperty('hidden way') //success new Creature().secretProperty = 'not permitted' // failure To r ...

How to extract a variable value from a different HTML page using jQuery

I have an HTML page named "page1.html" with the following content: <div> <div id="content"> content </div> <script type="text/javascript"> var x=5; var y=2; </script> <div id="ot ...

Clearing cookies in Express.js can be a challenging task

I've tried multiple options, but I can't seem to delete the cookie. Can anyone help me understand this? I have attempted using set maxage, expires, setheaders, but nothing seems to delete the cookie. It's impossible. res.cookie("refres ...

Trouble with Bootstrap 5 Dropdown Functionality

Currently, I am using Bootstrap 5 in conjunction with Django to create a website and I'm encountering difficulties with getting a dropdown feature to work properly. Despite copying the code directly from w3schools, it fails to function when I load the ...

Icon displayed within the input field

Is there a simple method to add an input text element with a clear icon on the right side, similar to the layout of the Google search box? I've searched, but I could only find instructions for placing an icon as the background of the input element. I ...

Exploring different pages in an Ionic and AngularJS mobile application

I am brand new to the world of Ionic and AngularJS. I have just started working on a simple project but have hit a roadblock. My goal is, To create a login page and a register page. When a user clicks the register button on the login page, they should be ...