Module: Mongoid::Memoization

Defined in:
lib/mongoid/memoization.rb

Instance Method Summary collapse

Instance Method Details

#memoized(name, &block) ⇒ Object

Handles cases when accessing an association that should be memoized in the Mongoid specific manner. Does not memoize nil values though



6
7
8
9
10
11
12
13
# File 'lib/mongoid/memoization.rb', line 6

def memoized(name, &block)
  var = "@#{name}"
  if instance_variable_defined?(var)
    return instance_variable_get(var)
  end
  value = yield
  instance_variable_set(var, value) if value
end

#reset(name, &block) ⇒ Object

Mongoid specific behavior is to remove the memoized object when setting the association, or if it wasn’t previously memoized it will get set.



23
24
25
26
27
28
29
30
31
# File 'lib/mongoid/memoization.rb', line 23

def reset(name, &block)
  var = "@#{name}"
  value = yield
  if instance_variable_defined?(var)
    remove_instance_variable(var)
  else
    instance_variable_set(var, value)
  end
end

#unmemoize(name) ⇒ Object

Removes an memozied association if it exists



16
17
18
19
# File 'lib/mongoid/memoization.rb', line 16

def unmemoize(name)
  var = "@#{name}"
  remove_instance_variable(var) if instance_variable_defined?(var)
end