Search code examples
ruby-on-rails-3activerecordresque

How to pass ActiveRecord model class to Resque


Let's say I have the following Resque job:

class Archive
  @queue = :file_serve

  def self.perform(repo_id, branch = 'master')
    repo = Repository.find(repo_id)
    repo.create_archive(branch)
  end
end

What if I wanted to make this more generic by passing an object id and the object's class so that I can do something like this:

class Archive
  @queue = :file_serve

  def self.perform(object_class, object_id, branch = 'master')
    object = object_class.find(object_id)
    object.create_archive(branch)
  end
end

This doesn't work, obviously, and I don't have a sense for what I should be doing, so if anyone can give some guidance, that would be really appreciated!


Solution

  • I would pass the name of the class to the job, rather than the class itself. Then you could call constantize on the name to get the class back, and call find on it. eg.

    def self.perform(class_name, object_id, branch = 'master')
      object = class_name.constantize.find(object_id)
      object.create_archive(branch)
    end