dchelimsky (owner)

Revisions

gist: 189324 Download_button fork
public
Public Clone URL: git://gist.github.com/189324.git
Embed All Files: show embed
Text only #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
module ResultCaching
  def with_result_caching
    begin
      @methods_to_cache = []
      @caching = true
      yield
      @caching = false
      @methods_to_cache.each do |name|
        alias_method "cached_#{name}", name
        class_eval <<-EOF
def #{name}
  @#{name} ||= send :cached_#{name}
end
EOF
      end
    ensure
      @methods_to_cache = nil
      @caching = false
    end
  end
  
  def method_added(name)
    if @caching
      @methods_to_cache << name
    end
    super
  end
end
 
class Foo
  extend ResultCaching
  
  with_result_caching do
    def bar
      @count ||= 0
      @count += 1
    end
  end
end
 
foo = Foo.new
puts foo.bar
puts foo.bar