Created
October 14, 2015 21:00
-
-
Save ksol/2aa776366da13a8881be to your computer and use it in GitHub Desktop.
method_added example 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Memoizer | |
| def self.memoize | |
| @memoized = true | |
| end | |
| def self.method_added(method_name) | |
| if @memoized | |
| # We're disabling memoization so that when we call "define_method", | |
| # we're not going to loop indefinitely | |
| @memoized = false | |
| # Getting the method as an object | |
| target_method = instance_method(method_name) | |
| # Overriding it ! | |
| define_method(method_name) do |*args, &blk| | |
| # Initializing the cache object | |
| @_memoize_storage ||= {} | |
| if @_memoize_storage[method_name] | |
| # Cached? Do not compute ! | |
| puts "Returning cached valued" | |
| else | |
| # Not cached? compute and store the result ! | |
| puts "Computing value" | |
| decorated = target_method.bind(self) | |
| @_memoize_storage[method_name] = decorated.call(*args, &blk) | |
| end | |
| # Return the cached result | |
| @_memoize_storage[method_name] | |
| end | |
| end | |
| end | |
| memoize | |
| def run | |
| sleep(3) | |
| 1 + 1 | |
| end | |
| end | |
| ### When defining the class, this is the output: | |
| # | |
| # :run | |
| ### When using an instance, this is the output: | |
| # | |
| # > t = Memoizer.new | |
| # => #<Memoizer:0x007fa2ce852c58> | |
| # | |
| # > t.run | |
| # Computing value | |
| # => 2 | |
| # | |
| # > t.run | |
| # Returning cached valued | |
| # => 2 | |
| # | |
| # Note that there was 3 seconds of pause between line 54 and 55, | |
| # while there was none between line 58 and 59. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment