Search code examples
ruby-on-railsrubysidekiq

Rails - Sidekiq error Uninitialized Constant


Can anyone tell me why I am getting the following error from Sidekiq:

NameError: uninitialized constant ImageWorker::DIRECT_UPLOAD_URL_FORMAT

app/models/choice.rb

class Choice < ActiveRecord::Base

 #Environment-specific direct upload url verifier screens for malicious posted upload locations.
  DIRECT_UPLOAD_URL_FORMAT = %r{\Ahttps:\/\/s3-us-west-1\.amazonaws\.com\/mybucket\/(?<path>uploads\/.+\/(?<filename>.+))\z}.freeze

  after_commit :queue_processing
  
  protected
  # Queue file processing
    def queue_processing
      ImageWorker.perform_async(id)
    end
end

app/workers/image_worker.rb

 class ImageWorker
   include Sidekiq::Worker
   
   def perform(id)
     choice = Choice.find(id)
     direct_upload_url_data = DIRECT_UPLOAD_URL_FORMAT.match(choice.direct_upload_url)
     s3 = AWS::S3.new

     if choice.post_process_required?
       choice.picture = URI.parse(URI.escape(choice.direct_upload_url))
     else
       paperclip_file_path = "documents/uploads/#{id}/original/#{direct_upload_url_data[:filename]}"
    s3.buckets[Rails.configuration.aws[:bucket]].objects[paperclip_file_path].copy_from(direct_upload_url_data[:path])
  end

  choice.processed = true
  choice.save

  s3.buckets[Rails.configuration.aws[:bucket]].objects[direct_upload_url_data[:path]].delete
  end
 end

Any help would be great!


Solution

  • You should move the following line to the ImageWorker class:

    DIRECT_UPLOAD_URL_FORMAT = %r{\Ahttps:\/\/s3-us-west-1\.amazonaws\.com\/mybucket\/(?<path>uploads\/.+\/(?<filename>.+))\z}.freeze
    

    Or, otherwise, use the complete qualified path for the constant: DIRECT_UPLOAD_URL_FORMAT like this:

    direct_upload_url_data = Choice::DIRECT_UPLOAD_URL_FORMAT.match(choice.direct_upload_url)
    

    At the moment, your code is trying to locate a constant named DIRECT_UPLOAD_URL_FORMAT inside the ImageWorker class, which is definitely not initialized, and hence, the error.