0

My base class is Premade which has two subclasses: PremadeController and PremadeControllerSession. They are very similar. For example. They both need to build records in MySQl in batches of 1000, but I want PremadeControllers to get built before so I have them going to different queues in Resque.

So the two sub classes look like this:

class PremadeController < Premade

  def self.maintain
    ((max_premade_count - premade_count)/batch_size).times do
      Resque.enqueue(Workers::BuildPremadeControllerJob)
    end
  end

end 

And:

class PremadeSessionController < Premade

  def self.maintain
    ((max_premade_count - premade_count)/batch_size).times do
      Resque.enqueue(Workers::BuildPremadeControllerSessionJob)
    end
  end

end 

The only difference between those methods is the worker class (i.e. BuildPremadeControllerSessionJob and BuildPremadeControllerJob)

I've tried to put this in the parent and dynamically defining the constant, but it does not work probably due to a scope issue. For example:

class Premade

  def self.maintain
    ((max_premade_count - premade_count)/batch_size).times do
      Resque.enqueue(Workers::)
    end
  end

end

What I want to do is define this method in the parent, such as:

def self.maintain
  ((max_premade_count - premade_count)/batch_size).times do
    Resque.enqueue(Workers::build_job_class)
  end
end

Where build_job_class is defined in each subclass.

Please don't tell me to change Resque's worker syntax because that is not the question I'm asking.

4

2 回答 2

3

你应该能够做到这一点const_get-

klass = Workers.const_get "Build#{self.name}Job"
于 2012-05-13T00:05:59.540 回答
1

这样做的一种build_job_class方法是在您的 2 个类上定义一个类方法,该类方法返回适当的工作类,即PremadeSessionController看起来像

class PremadeSessionController
  def self.build_job_class
    Workers::BuildPremadeControllerSessionJob
  end
end

然后将您的维护方法更改为

def self.maintain
  ((max_premade_count - premade_count)/batch_size).times do
    Resque.enqueue(build_job_class)
  end
end
于 2012-05-13T00:13:21.547 回答