Search code examples
javascriptjqueryruby-on-railssidekiqpolling

Polling Sidekiq Job for Completion via Processing State in Database


I'm attempting to show my users a simple message while their custom PDF is being created and attached to the model via Paperclip. Then display the preview once complete.

The simplest solution I can find is Mike Perham's response in this question. "Use the database to store the state of each photo and have Sidekiq update the state."

No doubt you will notice that I'm still learning Javascript, JQuery, Rails & how to write good SO questions. Nevertheless, here is what I have Frankenstein-ed so far.

Please let me know if I am working in the right direction here?

# generate_insert.rb
class GenerateInsert 
  include Sidekiq::Worker
  def perform(customization_id)
    customization = Customization.find(customization_id)
    customization.update_attribute(:processing, true)
    # code to perform, generate PDF via Prawn and attach via Paperclip
    customization.update_attribute(:processing, false)
    customization.save!
  end
end

# customizations/show.html.erb
<div id='message'>First Message</div>

# messages.js
var i = 1;
var sampleMessages = [ "First Message", "Second Message", "Third Message" ];
    setInterval(function() {
        var newText = sampleMessages[i++ % sampleMessages.length];
        $("#message").fadeOut(500, function () {
            $(this).text(newText).fadeIn(500);
        });
    }, 1 * 3000);
});

# show.js.erb
$("#message").replaceWith("<%= j render 'customization' %>");

# poller.js
CustomizationPoller =
poll: ->
    setTimeout @request, 5000

request: ->,
    $.get($('???').data('url'))

jQuery ->
if $('#???').length > 0 // customization processing?
    CustomizationPoller.poll()

Solution

  • With the tools you have you seem to be on the right track. Keeping it simple until your users demand more robust solution is IMHO a good idea.

    If you however are looking to have more interactions like this(i.e. user does something and waits for update) you may consider using web socket or even employing tools like https://rethinkdb.com . Of course it depends on how many interactions like this you're planning to have.