module ActiveRecord #:nodoc: module Associations #:nodoc: module Scope #:nodoc: def self.included(base) base.extend(ClassMethods) end module ClassMethods def with_association_scope(options = {}, &block) write_inheritable_attribute(:association_scope, options) class_eval { extend ActiveRecord::Associations::Scope::SingletonMethods } yield SingletonMethods.define_methods(self, true) end end module SingletonMethods def self.extend_object(base) define_methods(base) super end def self.define_methods(base, remove = false) extra = (remove ? "" : "association_scope_options!(options);") association_methods.each do |assoc| base.class_eval "def self.#{assoc}(assoc, options = {}) #{extra} super end" end end def self.association_methods [:has_many, :has_one, :has_and_belongs_to_many, :belongs_to] end def association_scope_options!(options = {}) return unless options.is_a? Hash options.reverse_merge! read_inheritable_attribute(:association_scope) end end end end end