3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# File 'lib/memist/class_methods.rb', line 3
def memoize(method)
if instance_method(method).arity > 1
raise ArgumentError, "Cannot memoize `#{method}` method because it accepts more than one argument."
end
define_method "#{method}_with_memoization" do |arg = nil|
@memoized_values ||= Hash.new { |hash, key| hash[key] = {} }
if @memoized_values.key?(method) && @memoized_values[method].key?(arg)
@memoized_values[method][arg]
else
@memoized_values[method][arg] = send("#{method}_without_memoization", *arg)
end
end
alias_method "#{method}_without_memoization", method
alias_method method, "#{method}_with_memoization"
end
|