views:

20

answers:

1

I want to override an existing scope to add an extra condition to it. I've shown my attempt to do this using alias_method. Unfortunately this approach doesn't work with scopes, I get an undefined method error. How do I do it with scopes?

module Delayed
  module Backend
    module ActiveRecord
      class Job < ::ActiveRecord::Base
        belongs_to :queue

        scope :in_unlocked_queue, lambda {
          joins(:queue) & Queue.unlocked
        }

        alias_method :orig_ready_to_run, :ready_to_run
        scope :ready_to_run, lambda {|worker_name, max_run_time|
          orig_ready_to_run(worker_name, max_run_time).in_unlocked_queue
        }
      end
    end
  end
end
+1  A: 

OK, here's an answer, not sure if it's the cleanest but it works

require 'delayed_job'

module Delayed
  module Backend
    module ActiveRecord
      class Job < ::ActiveRecord::Base
        belongs_to :queue

        scope :in_unlocked_queue, lambda {
          joins(:queue) & Queue.unlocked
        }

        scope :orig_ready_to_run, scopes[:ready_to_run]
        scope :ready_to_run, lambda {|worker_name, max_run_time|
          orig_ready_to_run(worker_name, max_run_time).in_unlocked_queue
        }
      end
    end
  end
end
opsb