Module: RubyExt::DeclarativeCache
- Defined in:
- lib/ruby_ext/more/declarative_cache.rb
Class Method Summary collapse
Class Method Details
.cache_method(klass, *methods) ⇒ Object
4 5 6 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 |
# File 'lib/ruby_ext/more/declarative_cache.rb', line 4 def cache_method klass, *methods methods.each do |method| klass.class_eval do escaped_method = escape_method method method_with_cache = :"#{escaped_method}_with_cache" method_without_cache = :"#{escaped_method}_without_cache" iv_check = "@#{escaped_method}_cache_check" iv = "@#{escaped_method}_cache" 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 |
.cache_method_with_params(klass, *methods) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/ruby_ext/more/declarative_cache.rb', line 34 def cache_method_with_params klass, *methods methods.each do |method| klass.class_eval do escaped_method = escape_method method method_with_cache = :"#{escaped_method}_with_cache" method_without_cache = :"#{escaped_method}_without_cache" iv_check = "@#{escaped_method}_cache_check" iv = "@#{escaped_method}_cache" 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 |