Created
February 2, 2018 12:28
-
-
Save stuartc/24ae883815929b792e167c8cd63334f8 to your computer and use it in GitHub Desktop.
Memoization Helper
This file contains 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
# Replaces repetitive memoization syntax: | |
# ``` | |
# def foo | |
# return @_foo if defined? @_foo | |
# @_foo = 'bar' | |
# end | |
# ``` | |
# | |
# Usage: | |
# | |
# ``` | |
# require 'memoize' | |
# | |
# class Foo | |
# def bar | |
# memoize { 'baz' } | |
# end | |
# end | |
# ``` | |
def memoize(meth = nil) | |
variable_name = "@_#{meth || caller_locations(1, 1)[0].label}".to_sym | |
receiver = binding.receiver | |
if receiver.instance_variable_defined?(variable_name) | |
receiver.instance_variable_get(variable_name) | |
else | |
receiver.instance_variable_set(variable_name, yield) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one @stuartc - am definitely gonna use this.