dkubb / memoizable

Memoize method return values
MIT License
111 stars 10 forks source link

Lazy loader / auto include #15

Closed bartoszkopinski closed 10 years ago

bartoszkopinski commented 10 years ago

Hello, I wanted to make memoize available across the project and I came up with this:

Class.class_eval do
  def memoize *args
    include ::Memoizable
    memoize *args
  end
end

But that's a bit ugly solution so just wanted to ask how would you recommend achieving this?

dkubb commented 10 years ago

@bartoszkopinski what's the use case for wanting to dynamically add memoization to a class?

Including a module, and rewriting a method will blow away your global method cache, so it's going to be comparatively expensive to do this dynamically as opposed to just including Memoizable in your class and using #memoize in your class definition.

bartoszkopinski commented 10 years ago

@dkubb It's not runtime dynamic if I got this right.

The point was to include only once if the class actually uses memoize as an alternative to including it in every class object like here. I think it's not much more expensive than explicit include. This gist should picture it better.

I was just wondering if you'd have a better solution by any chance.

dkubb commented 10 years ago

@bartoszkopinski oh heh, when I read Class in your example, I was thinking maybe you meant it as a stand-in for your class. I see now, you want to include it in every class in your system. You could just do this in a place that gets loaded early on:

Class.class_eval { include Memoizable }

The memoizable module doesn't really do much of anything, aside from adding the #memoize method so it should be safe if you want this behaviour globally available.