Module: DeclarativeCache
- Defined in:
- lib/ruby_ext/declarative_cache.rb
Constant Summary collapse
- DISABLED =
false
Class Method Summary collapse
Class Method Details
.cache_method(klass, *methods) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/ruby_ext/declarative_cache.rb', line 28 def cache_method klass, *methods methods.each do |method| klass.class_eval do als = "cached_#{escape_method(method)}" iv_check = "@#{als}_check" iv = "@#{als}" raise "Can't cache the #{method} twice!" if instance_methods.include?(als) alias_method als, method define_method method do |*args| raise "You tried to use cache without params for method with params (use 'cache_method_with_params' instead)!" unless args.empty? unless cached = instance_variable_get(iv) unless check = instance_variable_get(iv_check) cached = send als instance_variable_set iv, cached instance_variable_set iv_check, true end end cached end end end end |
.cache_method_with_params(klass, *methods) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/ruby_ext/declarative_cache.rb', line 54 def cache_method_with_params klass, *methods methods.each do |method| klass.class_eval do als = "cached_#{escape_method(method)}" iv = "@#{als}" raise "Can't cache the '#{method}' twice!" if instance_methods.include?(als) alias_method als, method define_method method 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 als, *args results[args] = result end result end end end end |