Class: Object

Inherits:
BasicObject
Defined in:
lib/rhr/core_ext/object.rb

Instance Method Summary collapse

Instance Method Details

#cmemoize(*method_names) ⇒ Object

Memoize class methods



21
22
23
24
25
# File 'lib/rhr/core_ext/object.rb', line 21

def cmemoize(*method_names)
  (class << self; self; end).class_eval do
    memoize(*method_names)
  end
end

#memoize(*names) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/rhr/core_ext/object.rb', line 2

def memoize(*names)
  names.each do |name|
    unmemoized = "__unmemoized_#{name}"
    class_eval %{
      alias   :#{unmemoized} :#{name}
      private :#{unmemoized}
      def #{name}(*args)
        cache = (@#{unmemoized} ||= {})
        if cache.has_key?(args)
          cache[args]
        else
          cache[args] = send(:#{unmemoized}, *args).freeze
        end
      end
    }
  end
end