9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
# File 'lib/correct_horse_battery_staple/memoize.rb', line 9
def memoize(method)
old_method = "_#{method}_unmemoized".to_sym
miss_object = Object.new
alias_method old_method, method
define_method method do |*args, &block|
@_memoize_mutex ||= Mutex.new
@_memoize_cache ||= {}
@_memoize_mutex.synchronize do
methcache = (@_memoize_cache[method] ||= {})
if block
raise ArgumentError, "You cannot call a memoized method with a block! #{method}"
end
value = methcache.fetch(args, miss_object)
if value === miss_object
value = methcache[args] = send(old_method, *args)
end
value
end
end
end
|