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.3"
Class Method Summary collapse
-
.extended(base) ⇒ void
private
Called when Memosa is extended.
-
.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
.extended(base) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Called when Memosa is extended
13 14 15 |
# File 'lib/memosa.rb', line 13 def self.extended(base) base.prepend(Initializer) end |
.reset(object) ⇒ void
This method returns an undefined value.
Reset an object’s memoization cache
87 88 89 90 91 |
# File 'lib/memosa.rb', line 87 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.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/memosa.rb', line 35 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.
72 73 74 75 76 77 78 |
# File 'lib/memosa.rb', line 72 def prepend_memosa if const_defined?(:MemosaMethods, false) const_get(:MemosaMethods, false) else const_set(:MemosaMethods, Module.new).tap { |mod| prepend(mod) } end end |