Module: Mongo::Model::Scope::ClassMethods

Defined in:
lib/mongo/model/scope.rb

Instance Method Summary collapse

Instance Method Details

#count(selector = {}, options = {}) ⇒ Object

finders



60
61
62
63
64
65
66
# File 'lib/mongo/model/scope.rb', line 60

def count selector = {}, options = {}
  if current = current_scope
    super current.selector.merge(selector), current.options.merge(options)
  else
    super selector, options
  end
end

#current_scopeObject



3
4
5
6
7
8
9
10
11
12
# File 'lib/mongo/model/scope.rb', line 3

def current_scope
  scope, exclusive = Thread.current[:mongo_model_scope]
  current = if exclusive
    scope
  elsif scope
    default_scope ? default_scope.merge(scope) : scope
  else
    default_scope
  end
end

#default_scope(*args, &block) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/mongo/model/scope.rb', line 39

def default_scope *args, &block
  if block
    self._default_scope = -> {query block.call}
  elsif !args.empty?
    self._default_scope = -> {query *args}
  else
    _default_scope && _default_scope.call
  end
end

#each(selector = {}, options = {}, &block) ⇒ Object



76
77
78
79
80
81
82
# File 'lib/mongo/model/scope.rb', line 76

def each  selector = {}, options = {}, &block
  if current = current_scope
    super current.selector.merge(selector), current.options.merge(options), &block
  else
    super selector, options, &block
  end
end

#first(selector = {}, options = {}) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/mongo/model/scope.rb', line 68

def first  selector = {}, options = {}
  if current = current_scope
    super current.selector.merge(selector), current.options.merge(options)
  else
    super selector, options
  end
end

#scope(name, *args, &block) ⇒ Object



49
50
51
52
53
54
# File 'lib/mongo/model/scope.rb', line 49

def scope name, *args, &block
  model = self
  metaclass.define_method name do
    query (block && instance_eval(&block)) || args
  end
end

#with_exclusive_scope(*args, &block) ⇒ Object



14
15
16
# File 'lib/mongo/model/scope.rb', line 14

def with_exclusive_scope *args, &block
  with_scope *(args << true), &block
end

#with_scope(*args, &block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mongo/model/scope.rb', line 18

def with_scope *args, &block
  if args.last.is_a?(TrueClass) or args.last.is_a?(FalseClass)
    exclusive = args.pop
  else
    exclusive = false
  end

  scope = query *args
  previous_scope, previous_exclusive = Thread.current[:mongo_model_scope]
  raise "exclusive scope already applied!" if previous_exclusive

  begin
    scope = previous_scope.merge scope if !exclusive and previous_scope
    Thread.current[:mongo_model_scope] = [scope, exclusive]
    return block.call
  ensure
    Thread.current[:mongo_model_scope] = [previous_scope, false]
  end
end