Skip to content

Instantly share code, notes, and snippets.

@onyxblade
Last active June 1, 2023 23:29
Show Gist options
  • Save onyxblade/e14a2d3b8c75c0557d985a7a4ab6c689 to your computer and use it in GitHub Desktop.
Save onyxblade/e14a2d3b8c75c0557d985a7a4ab6c689 to your computer and use it in GitHub Desktop.
A dead simple memoize library for Ruby
# 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