Amol Pujari Amol Pujari - 5 months ago 18
Ruby Question

Define all or most of the functions in a class with memoization by name

I have several methods with good human names, and I end up having memoization for each one, for example:

class MyClass
def one_good_name
@one_good_name ||= some good logic ...
end
end


I am looking for one class level method or some one-line way to make it. Instead of defining
@method_name ||=
everywhere, is there some magic like:

attr_accessor_memoizied :one_good_name, ...


which won't accept any args?

Answer

I'd recommend implementing this with the memoist ruby gem:

require 'memoist'
class MyClass
  extend Memoist
  def one_good_name
    # some good logic ...
  end

  memoize :one_good_name
end
Comments