Search code examples
ruby-on-railsrubyactiverecordresquerails-activejob

How to use ActiveJob (Resque Adapter) with Rails no ActiveRecord (using Mongoid)


I've been using Mongoid Adapter with Rails for an app. So I basically set the project up to not use ActiveRecord (since I'll also be deploying this to Heroku). I followed a tutorial and it worked for me:

Remove database adapter gems from your Gemfile, e.g., mysql2, sqlite3, etc

From application.rb, remove require 'rails/all' and add

require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"

Delete database.yml, schema.rb and all the migrations
Delete migration checks from test/test_helper.rb
Delete all activerecord related configuration from config/environments

However, now - as I am optimizing the processes in my web app (an import csv process), I decided to use delayed jobs using ActiveJob + Resque.

I understand that I needed Redis for Resque and so I installed that and ran the server, however the rake task setup for Resque looks like this:

require 'resque/tasks'

task "resque:setup" => :environment do
  Resque.before_fork = Proc.new do |job|
    ActiveRecord::Base.connection.disconnect!
  end
  Resque.after_fork = Proc.new do |job|
    ActiveRecord::Base.establish_connection
  end
end

It seems to need ActiveRecord to do its job (of course since it is mapping to the redis database). And without surprise when I ran this:

LOGGING=1 QUEUE=* bundle exec rake resque:work

It spews out an error (since ActiveRecord is missing):

*** Failed to start worker : #<NameError: uninitialized constant ActiveRecord>

How do I make this work?


Solution

  • I know this was asked awhile ago but the answer here is that you can safely remove the before/after work procs with your own resque.rake

    Here is mine:

    #lib/tasks/resque.rake
    
    require 'resque/tasks'
    require 'resque/scheduler/tasks'
    
    namespace :resque do 
        task setup: :setup_logger do #setup logger includes environment!
            require 'resque'
            require 'resque-scheduler'
        end
     end
    
    
    #Sets up logging - should only be called from other rake tasks
    task setup_logger: :environment do
        logger           = Logger.new(STDOUT)
        logger.level     = Logger.const_get((ENV["LOG_LEVEL"] || "DEBUG").upcase)
        Rails.logger     = logger
    end