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.3"

Class Method Summary collapse

Instance Method Summary collapse

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

Parameters:

  • base (Module)


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

Examples:

Memosa.reset(user)

Parameters:

  • object (Object)


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.

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



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_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)


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