Module: MethodCacher

Defined in:
lib/basiccache/methodcacher.rb

Overview

Helper module for caching methods inside a class To use, extend your class with MethodCacher Then, in initialize, call enable_caching

Instance Method Summary collapse

Instance Method Details

#enable_caching(methods, cache = nil) ⇒ Object

Enable caching for the listed methods


9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/basiccache/methodcacher.rb', line 9

def enable_caching(methods, cache = nil)
  cache ||= BasicCache.new
  methods.each do |name|
    uncached_name = "#{name}_uncached".to_sym
    singleton_class.class_eval do
      alias_method uncached_name, name
      define_method(name) do |*a, &b|
        cache.cache(name) { send uncached_name, *a, &b }
      end
    end
  end
end