Module: Nanoc3::Memoization
- Included in:
- Compiler, Item, Layout, OutdatednessChecker, RuleMemoryCalculator, RulesCollection
- Defined in:
- lib/nanoc3/base/memoization.rb
Overview
Adds support for memoizing functions.
Instance Method Summary collapse
-
#memoize(method_name) ⇒ void
Memoizes the method with the given name.
Instance Method Details
#memoize(method_name) ⇒ void
This method returns an undefined value.
Memoizes the method with the given name. The modified method will cache the results of the original method, so that calling a method twice with the same arguments will short-circuit and return the cached results immediately.
Memoization assumes that the current object as well as the function arguments are immutable. Mutating the object or the arguments will not cause memoized methods to recalculate their results. There is no way to un-memoize a result, and calculation results will remain in memory even if they are no longer needed.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/nanoc3/base/memoization.rb', line 43 def memoize(method_name) # Alias original_method_name = '__nonmemoized_' + method_name.to_s alias_method original_method_name, method_name # Redefine define_method(method_name) do |*args| # Get cache @__memoization_cache ||= {} @__memoization_cache[method_name] ||= {} # Recalculate if necessary if !@__memoization_cache[method_name].has_key?(args) result = send(original_method_name, *args) @__memoization_cache[method_name][args] = result end # Done @__memoization_cache[method_name][args] end end |