开发者

Override a scope in rails 3

开发者 https://www.devze.com 2023-01-21 00:02 出处:网络
I want to override an existing scope to开发者_如何学Python 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

I want to override an existing scope to开发者_如何学Python 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消