Module: Memosa
- Defined in:
- lib/memosa.rb,
lib/memosa/cache.rb,
lib/memosa/version.rb,
lib/memosa/internal.rb
Overview
Memosa provides a simple way to memoize methods in Ruby.
Defined Under Namespace
Constant Summary collapse
- VERSION =
The current Memosa version
"0.8.0"
Class Method Summary collapse
-
.reset(object) ⇒ void
Reset an object’s memoization cache.
Instance Method Summary collapse
-
#memoize(method_name) ⇒ Symbol
Convert a method to a memoized method.
-
#prepend_memosa ⇒ Module
Define and prepend MemosaMethods.
Class Method Details
.reset(object) ⇒ void
This method returns an undefined value.
Reset an object’s memoization cache
81 82 83 84 85 |
# File 'lib/memosa.rb', line 81 def self.reset(object) cache = object.instance_variable_get(:@_memosa_cache) cache&.clear nil end |
Instance Method Details
#memoize(method_name) ⇒ Symbol
Convert a method to a memoized method
Memosa does not support memoizing methods that accept arguments.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/memosa.rb', line 27 def memoize(method_name) methods = prepend_memosa visibility = Internal.visibility(self, method_name) if Internal.method_defined?(methods, method_name) raise ArgumentError, "`#{method_name.inspect}` is already memoized" end methods.module_eval(" \#{visibility} def \#{method_name}\n raise ArgumentError, \"unsupported block argument\" if block_given?\n\n cache = (@_memosa_cache ||= {})\n cache.fetch(:\#{method_name}) do\n cache[:\#{method_name}] = super()\n end\n end\n RUBY\n\n method_name\nend\n", __FILE__, __LINE__ + 1) |
#prepend_memosa ⇒ Module
Define and prepend MemosaMethods
When #memoize is called, Memosa will define a module named MemosaMethods. Memoized methods will be defined on this module and then prepended to the class.
This method allows you to force that module to be defined and prepended, which is useful when order matters.
64 65 66 67 68 69 70 71 72 |
# File 'lib/memosa.rb', line 64 def prepend_memosa prepend Initializer if const_defined?(:MemosaMethods, false) const_get(:MemosaMethods, false) else const_set(:MemosaMethods, Module.new).tap { |mod| prepend(mod) } end end |