Module: ContextAwareScope

Included in:
ActiveRecord::NamedScope::Scope
Defined in:
lib/context_aware_scope.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/context_aware_scope.rb', line 2

def self.included(base)
  base.class_eval do
    extend ClassMethods
    class_eval do
      def initialize_with_context(proxy_scope, options, &block)
        @context = options ? options[:context] || {} : {}
        initialize_without_context(proxy_scope, options, &block)
      end

      alias_method_chain :initialize, :context

      # get current context from scope chain
      def context
        if @proxy_scope.class == ActiveRecord::NamedScope::Scope
          recursive_context = @proxy_scope.context
          recursive_context = recursive_context.keep_merge(@context)
          recursive_context
        else
          # add default scope context if on active_record
          default_scoping.inject(@context){|context, scope| context.keep_merge(scope[:find][:context] || {})}
        end
      end

      # exclude context from proxy options
      # that way it is not sent to the with_scope on the ActiveRecord model
      def proxy_options
        @proxy_options.except(:context)
      end
    end
  end
end