matthewrudy / memoist

ActiveSupport::Memoizable with a few enhancements
MIT License
921 stars 99 forks source link

Enable to set value to memoized method externally #18

Open ryoqun opened 10 years ago

ryoqun commented 10 years ago

Thanks for creating and maintaining this gem. :) We're currently evaluating to use this gem in our production code.

This pull request changes API. Namely it adds a new instance method called set_cache. This method can be used to set a memoized method to value from external.

In our code base, we need to assign the same value to huge number of objects at once in the batch processing for further manipulation of these objects.

In such a case, we would like to reuse the same object computed once at the entry point before the hot loop instead of repeatedly calling the memoized method for each and every objects.

So we'd like to have an official API to do that.

ryoqun commented 10 years ago

If this is sounds good to add, bumping a version is +1. :)

matthewrudy commented 10 years ago

Hi @ryoqun, I mostly maintain this for legacy support. So I'm not sure I want to add new features.

But I wonder why you don't take a different approach if this is fresh code. For doing something similar in my current project I do this

class User
  def comments
    @comments ||= find_comments
  end

  def sideload_comments(comments)
    @comments = comments
  end

  private

  def find_comments
    # some assumedly slow task to load comments
  end
end

Then your multi-user comment loader is something like.

def sideload_comments(users)
  all_comments = find_comments_for_users(users)
  users.zip(all_comments) do |user, comments|
    user.sideload_comments(comments)
  end
end