Last active
June 1, 2023 23:29
-
-
Save onyxblade/e14a2d3b8c75c0557d985a7a4ab6c689 to your computer and use it in GitHub Desktop.
A dead simple memoize library for Ruby
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
# There are many fancier memoize libraries out there: | |
# https://github.com/tycooon/memery | |
# https://github.com/makandra/memoized | |
# Some of them support expiration, some memoizing methods with arguments. | |
# However, I just want a dead simple implementation that memoizes getters only. | |
module Memoist | |
def memoize name | |
if instance_method(name).arity != 0 | |
raise "Only methods without arguments are supported by `memoize`." | |
else | |
@_memoist_module ||= begin | |
mod = Module.new | |
prepend mod | |
mod | |
end | |
key = "@_memoized_#{name}".to_sym | |
@_memoist_module.define_method(name) do | |
if instance_variable_defined?(key) | |
instance_variable_get(key) | |
else | |
instance_variable_set(key, super()) | |
end | |
end | |
end | |
end | |
end | |
Class.include Memoist | |
# In memory of Matthew Rudy Jacobs who built the original memoist library: | |
# https://github.com/matthewrudy/memoist |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment