Created
October 16, 2015 07:50
-
-
Save ksol/9782e9131e1d779580e1 to your computer and use it in GitHub Desktop.
Example without decorators
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(method_name) | |
| # 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 | |
| memoize def run | |
| sleep(3) | |
| 1 + 1 | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment