Module: DeclarativeCache
- Defined in:
- lib/ruby_ext/more/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 53 54 55 56 57 |
# File 'lib/ruby_ext/more/declarative_cache.rb', line 28 def cache_method klass, *methods methods.each do |method| klass.class_eval do escaped_method = escape_method(method) method_with_cache, method_without_cache = "#{escaped_method}_with_cache".to_sym, "#{escaped_method}_without_cache".to_sym iv_check = "@#{escaped_method}_cache_check" iv = "@#{escaped_method}_cache" 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 define_method method_with_cache 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 method_without_cache instance_variable_set iv, cached instance_variable_set iv_check, true end end cached end alias_method method, method_with_cache end end end end |
.cache_method_with_params(klass, *methods) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/ruby_ext/more/declarative_cache.rb', line 59 def cache_method_with_params klass, *methods methods.each do |method| klass.class_eval do escaped_method = escape_method(method) method_with_cache, method_without_cache = "#{escaped_method}_with_cache".to_sym, "#{escaped_method}_without_cache".to_sym iv_check = "@#{escaped_method}_cache_check" iv = "@#{escaped_method}_cache" 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 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 alias_method method, method_with_cache end end end end |