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

Modules: API Classes: Cache

Constant Summary collapse

VERSION =

The current Memosa version

Returns:

  • (String)
"0.8.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.reset(object) ⇒ void

This method returns an undefined value.

Reset an object’s memoization cache

Examples:

Memosa.reset(user)

Parameters:

  • object (Object)


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.

Examples:

class State
  extend Memosa

  memoize def id
    SecureRandom.uuid
  end
end

Parameters:

  • method_name (Symbol)

    the name of the method to memoize

Returns:

  • (Symbol)

    the name of the memoized method

Raises:

  • (ArgumentError)

    when the method is is not defined

  • (ArgumentError)

    when the method is already memoized



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_memosaModule

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.

Examples:

class Foo
  extend Memosa
  prepend_memosa
end

Returns:

  • (Module)


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