Sha256: d4c54746a4e744d0fdd0257ced7232b8f4fec0b3b29879fae59201647ffbb8eb

Contents?: true

Size: 883 Bytes

Versions: 3

Compression:

Stored size: 883 Bytes

Contents

require "mem/version"

module Mem
  def self.included(base)
    base.extend(ClassMethods)
  end

  def has_memoized?(key)
    memoized_table.key?(key)
  end

  def memoize(key, value)
    memoized_table[key] = value
  end

  def memoized(key)
    memoized_table[key]
  end

  def memoized_table
    @memoized_table ||= {}
  end

  module ClassMethods
    def memoize(method_name)
      define_method("#{method_name}_with_memoize") do |*args, &block|
        if has_memoized?(method_name)
          memoized(method_name)
        else
          memoize(method_name, send("#{method_name}_without_memoize", *args, &block))
        end
      end
      alias_method "#{method_name}_without_memoize", method_name
      alias_method method_name, "#{method_name}_with_memoize"

      define_method("#{method_name}=") do |value|
        memoize(method_name, value)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mem-0.1.3 lib/mem.rb
mem-0.1.2 lib/mem.rb
mem-0.1.1 lib/mem.rb