Sha256: b4d2211c68332effe2877cee2b189d6b09d10ea07ac52694717003e833930175

Contents?: true

Size: 1.38 KB

Versions: 24

Compression:

Stored size: 1.38 KB

Contents

class Module
  
  # 
  # Dynamically enables cache in :production and disables in another environments.
  # If no environment given uses non-cached version.
  # 
  def cache_method_with_params_in_production method        
    escaped_method = escape_method(method)
    method_with_cache, method_without_cache = "#{escaped_method}_with_cache", "#{escaped_method}_without_cache"
    iv = "@#{escaped_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

      if rad.mode == :production
        alias_method method, method_with_cache
      else
        alias_method method, method_without_cache
      end

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

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
rad_core-0.2.6 lib/rad/_support/module.rb
rad_core-0.2.5 lib/rad/_support/module.rb
rad_core-0.2.4 lib/rad/_support/module.rb
rad_core-0.2.3 lib/rad/_support/module.rb
rad_core-0.2.2 lib/rad/_support/module.rb
rad_core-0.2.1 lib/rad/_support/module.rb
rad_core-0.2.0 lib/rad/_support/module.rb
rad_core-0.0.30 lib/rad/_support/module.rb
rad_core-0.0.29 lib/rad/_support/module.rb
rad_core-0.0.28 lib/rad/_support/module.rb
rad_core-0.0.27 lib/rad/_support/module.rb
rad_core-0.0.26 lib/rad/_support/module.rb
rad_core-0.0.25 lib/rad/_support/module.rb
rad_core-0.0.24 lib/rad/_support/module.rb
rad_core-0.0.23 lib/rad/_support/module.rb
rad_core-0.0.22 lib/rad/_support/module.rb
rad_core-0.0.21 lib/rad/_support/module.rb
rad_core-0.0.20 lib/rad/_support/module.rb
rad_core-0.0.19 lib/rad/_support/module.rb
rad_core-0.0.18 lib/rad/_support/module.rb