Class: Module

Inherits:
Object show all
Defined in:
lib/rad/support/module.rb

Instance Method Summary collapse

Instance Method Details

#cache_method_with_params_in_production(method) ⇒ Object

Dynamically enables cache in :production and disables in another environments. If no environment given uses non-cached version.



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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rad/support/module.rb', line 7

def cache_method_with_params_in_production method        
  method_with_cache, method_without_cache = "#{method}_with_cache", "#{method}_without_cache"
  iv = "@#{method}_cache"
  
  # raise "Method '#{method}' already defined!" if instance_methods.include?(method)
  if instance_methods.include?(method_with_cache) or instance_methods.include?(method_without_cache)
    warn "can't cache the :#{method} twice!" 
  else
    alias_method method_without_cache, method      

    # create cached method
    define_method method_with_cache do |*args| 
      unless results = instance_variable_get(iv)
        results = Hash.new(NotDefined)
        instance_variable_set iv, results
      end

      result = results[args]

      if result.equal? NotDefined 
        result = send method_without_cache, *args
        results[args] = result
      end

      result
    end

    # listen to environment events
    rad.after :config do |config|
      if config.production?
        alias_method method, method_with_cache
      else
        alias_method method, method_without_cache
      end
    end

    # by default uses non-cached version
    # alias_method method, method_without_cache
  end        
end