8

Hey we have a library class (lib/Mixpanel) that calls delayed job as follows:

class Mixpanel

  attr_accessor :options
  attr_accessor :event

  def track!()
   .. 
   dj = send_later :access_api # also tried with self.send_later
   ..
  end

  def access_api
   ..
  end

The problem is that when we run rake jobs:work: we get the following error:

undefined method `access_api' for #<YAML::Object:0x24681b8>

Any idea why?

Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
LMH
  • 949
  • 9
  • 22
  • Seems like the delayed job doesn't know about your library class so it just becomes a YAML::Object, sorry I don't know how you can get it load your library class. – Corey Apr 03 '10 at 02:22
  • I noticed that this problem exists with anything that is not an `ActiveRecord` model. My PORO is in `app/models` and normally, it's auto-loaded by Rails. `delayed_job` seems to have a problem with it, unless I use the initializer solution described below by Jonathan. – Kenrick Chien Aug 27 '13 at 19:30

2 Answers2

16

Delayed_job always autoloads ActiveRecord classes, but it doesn't know about other types of classes (like lib) that it has marshaled in the db as YML. So, you need to explicitly trigger the class loader for them. Since DJ starts up the Rails environment, just mention any non-AR marshaled classes in an initializer:

(config/initializers/load_classes_for_dj.rb)

Mixpanel
Jonathan Julian
  • 12,163
  • 2
  • 42
  • 48
2

A small gotcha, I followed Jonathan's suggestion, but I needed to add a require before the class name, so I'd use this for load_classes_for_dj.rb:

require 'mixpanel'
Mixpanel

Then it worked fine!

ice cream
  • 2,444
  • 2
  • 17
  • 13
  • Having config.autoload_paths += %W(#{config.root}/lib) in config/application.rb would require all the classes in lib in case you have a lot of files to require =) – Abdo Feb 21 '13 at 09:27