Module: Memoit

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

Constant Summary collapse

VERSION =
"0.2.0"

Instance Method Summary collapse

Instance Method Details

#memoize(name) ⇒ Object

Memoize the method with the given name.

Examples:

class Foo
  memoize def bar(value)
    expensive_calculation(value)
  end
end


13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/memoit.rb', line 13

def memoize(name)
  ivar_name = "@_memo_#{name}".to_sym
  mod = Module.new do
    define_method(name) do |*args, &block|
      return super(*args, &block) if block
      cache = instance_variable_get(ivar_name) || instance_variable_set(ivar_name, {})
      cache.fetch(args.hash) { |hash| cache[hash] = super(*args) }
    end
  end
  prepend mod
  name
end

#memoize_class_method(name) ⇒ Object

Memoize the class method with the given name.

Examples:

class Foo
  memoize_class_method def self.bar(value)
    expensive_calculation(value)
  end
end


34
35
36
# File 'lib/memoit.rb', line 34

def memoize_class_method(name)
  singleton_class.memoize(name)
end