Skip to content

Instantly share code, notes, and snippets.

@joeldrapper
Last active December 13, 2022 12:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeldrapper/7e35f2f5f906344195c121801ddd28d4 to your computer and use it in GitHub Desktop.
Save joeldrapper/7e35f2f5f906344195c121801ddd28d4 to your computer and use it in GitHub Desktop.
Attribute Memoization
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