Sha256: d6e01fce248a23fa149a3fd88440246e50bfc45d1580fbad462585173d508fc8

Contents?: true

Size: 1.25 KB

Versions: 3

Compression:

Stored size: 1.25 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        
    method_with_cache, method_without_cache = "#{method}_with_cache", "#{method}_without_cache"
    iv = "@#{method}_cache"
    
    raise "Method '#{method}' already defined!" if instance_methods.include?(method)
    raise "Can't cache the '#{method}' twice!" if instance_methods.include?(method_with_cache)
        
    # 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 als, *args
        results[args] = result
      end
    
      result
    end
        
    # listen to environment events
    crystal.after :config do |config|
      if config.production?
        alias_method method, method_with_cache
      else
        alias_method method, method_without_cache
      end
    end
    
    # by default uses non-cached version
    alias_method method, method_without_cache
  end
  
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
crystal-0.0.13 lib/crystal/support/module.rb
crystal-0.0.12 lib/crystal/support/module.rb
crystal_ext-0.0.11 lib/crystal/support/module.rb