Module: MongoMapper::Plugins::Scopes::ClassMethods

Defined in:
lib/mongo_mapper/plugins/scopes.rb

Instance Method Summary collapse

Instance Method Details

#active_scopesObject



33
34
35
# File 'lib/mongo_mapper/plugins/scopes.rb', line 33

def active_scopes
  Thread.current["mongo_mapper_#{name}_active_scopes"] ||= []
end

#default_scope(*args, &block) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/mongo_mapper/plugins/scopes.rb', line 57

def default_scope(*args, &block)
  if block_given?
    default_scopes << instance_exec(&block)
  end

  if args.any?
    default_scopes << args
  end

  default_scopes
end

#default_scopesObject



37
38
39
40
41
42
43
# File 'lib/mongo_mapper/plugins/scopes.rb', line 37

def default_scopes
  @default_scopes ||= begin
    superclass.respond_to?(:default_scopes) ?
      superclass.default_scopes.dup :
      []
  end
end

#query(options = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/mongo_mapper/plugins/scopes.rb', line 45

def query(options = {})
  res = super(options)

  all_anonymous_scopes.each do |scope|
    unscoped do
      res = process_scope(res, scope)
    end
  end

  res
end

#scope(name, scope = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/mongo_mapper/plugins/scopes.rb', line 12

def scope(name, scope={})
  if dangerous_class_method?(name)
    raise ArgumentError, <<~end_message
      You tried to define a scope named "#{name}"
      on the model "#{self.name}", but MongoMapper::Document already defined
      a class method with the same name.
    end_message
  end

  # Assign to _scopes instead of using []= to avoid mixing subclass scopes
  self._scopes = scopes.merge(name => scope)

  singleton_class.send :define_method, name do |*args|
    process_scope(self, scopes[name], *args)
  end
end

#scopesObject



29
30
31
# File 'lib/mongo_mapper/plugins/scopes.rb', line 29

def scopes
  self._scopes ||= {}
end

#unscopedObject



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/mongo_mapper/plugins/scopes.rb', line 76

def unscoped
  old_default_scopes = default_scopes.dup
  old_active_scopes = active_scopes.dup

  @default_scopes = []
  active_scopes.clear

  yield
ensure
  @default_scopes = old_default_scopes
  active_scopes.concat(old_active_scopes)
end

#with_scope(query = {}) ⇒ Object



69
70
71
72
73
74
# File 'lib/mongo_mapper/plugins/scopes.rb', line 69

def with_scope(query = {})
  active_scopes.push(query)
  yield
ensure
  active_scopes.pop
end