Sha256: 1fe7e41face0c9eba35597019470dcda667d7a7942cf693a60e901b7d5811a32

Contents?: true

Size: 701 Bytes

Versions: 12

Compression:

Stored size: 701 Bytes

Contents

class Module

  #
  # Cache (memoize) the result of an instance method the first time
  # it's called, storing this value in the "@__memoized_#{methodname}_cache"
  # instance variable, and always return this value on subsequent calls
  # (unless the returned value is nil).
  #
  def memoize(*methods)
    # alias_method is faster than define_method + old.bind(self).call
    methods.each do |meth|
      alias_method "__memoized__#{meth}", meth
      module_eval <<-EOF
        def #{meth}(*a, &b)
          # assumes the block won't change the result if the args are the same
          (@__memoized_#{meth}_cache ||= {})[a] ||= __memoized__#{meth}(*a, &b)
        end
      EOF
    end
  end

end  

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
epitools-0.5.136 lib/epitools/core_ext/module.rb
epitools-0.5.134 lib/epitools/core_ext/module.rb
epitools-0.5.133 lib/epitools/core_ext/module.rb
epitools-0.5.131 lib/epitools/core_ext/module.rb
epitools-0.5.130 lib/epitools/core_ext/module.rb
epitools-0.5.129 lib/epitools/core_ext/module.rb
epitools-0.5.128 lib/epitools/core_ext/module.rb
epitools-0.5.126 lib/epitools/core_ext/module.rb
epitools-0.5.125 lib/epitools/core_ext/module.rb
epitools-0.5.124 lib/epitools/core_ext/module.rb
epitools-0.5.123 lib/epitools/core_ext/module.rb
epitools-0.5.122 lib/epitools/core_ext/module.rb