Module: Pakiderm

Defined in:
lib/pakiderm.rb,
lib/pakiderm/version.rb

Overview

Public: Mixin that adds memoization functionality to a plain ruby object. Memoization is selectively applied to methods by using the ‘memoize` method.

Examples

class PersonQuery
  extend Pakiderm

  memoize \
  def recent_activity
    NSA.get("/api/#{person.id}")
  end
end

Constant Summary collapse

VERSION =
'2.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.memoized_ivar_for(name) ⇒ Object

Internal: Creates a valid name for the instance variable used to store the memoized value for a method.

name - Name of the method to memoize.

Returns a String.


47
48
49
# File 'lib/pakiderm.rb', line 47

def self.memoized_ivar_for(name)
  "@pakiderm_#{ name.to_s.gsub('?', '_question_mark').sub('!', '_bang') }"
end

Instance Method Details

#memoize(*names) ⇒ Object

Public: Adds memoization to methods without parameters using Module#prepend.

names - Names of the methods to be memoized.

Examples

memoize :tired?, :complex_formula, :long_running_method!

Returns nothing.


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/pakiderm.rb', line 25

def memoize(*names)
  prepend Module.new {
    names.each do |name|
      ivar = Pakiderm.memoized_ivar_for(name)

      define_method(name) {
        if instance_variable_defined?(ivar)
          instance_variable_get(ivar)
        else
          instance_variable_set(ivar, super())
        end
      }
    end
  }
end