Posts tagged ‘memoize’

I have a singleton method in one of my service calls which I wanted to have memoize functionality. While there are several ways to do, I wanted to have a simple elegant way to do it. I have seen an example from Dave Thomas for instance methods. This one is similar to one of his examples but works for singleton methods. Comments are welcome. :)

module CacheHelper
  def cache(name)
    eigen_class = class << self
      self
    end
    eigen_class.instance_eval do
      memory = {}
      original = "original#{name}"
      alias_method(original, name)
      define_method(name) do |*args|
        if memory.has_key?(args)
          memory[args]
        else
          memory[args] = send original, *args
        end
      end
    end
  end
end