Last active
December 13, 2022 12:24
-
-
Save joeldrapper/7e35f2f5f906344195c121801ddd28d4 to your computer and use it in GitHub Desktop.
Attribute Memoization
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
module AttributeMemoization | |
def attr_accessor(*names, &block) | |
return super(*names) unless block_given? | |
attr_reader(*names, &block) | |
attr_writer(*names) | |
end | |
def attr_reader(*names, &block) | |
return super(*names) unless block_given? | |
names.each do |name| | |
define_method("_calculate_#{name}", &block) | |
class_eval(<<-RUBY, __FILE__, __LINE__ + 1) | |
def #{name} | |
return @#{name} if defined? @#{name} | |
@#{name} = _calculate_#{name} | |
end | |
RUBY | |
end | |
end | |
end | |
Module.prepend(AttributeMemoization) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment