ruby-on-railsrubymemoization

Memoize multi-line method - Rails


I've never implemented memoization before using rails, and I think I came across a good use case for it but I'm not sure how to do it. Here is what I'm working with:

METHOD:

 def manager_rep_code_and_name
    manager = []

    rep_code_list.each do |rep_code|
      context = Finfolio::GetManagerByRepCode.call(rep_code: rep_code)

      manager.push({name: context.manager.response.first["Name"], rep_code: rep_code})
    end

    manager
  end

This method makes a network call and can potentially take awhile to figure all this out. Is there a way I can memoize this method so if it already exists I don't have to go out and make this request again.

Something like this:

def manager_rep_code_and_name
   @managers ||= manager = []

   rep_code_list.each do |rep_code|
     context = Finfolio::GetManagerByRepCode.call(rep_code: rep_code)

     manager.push({name: context.manager.response.first["Name"], rep_code: rep_code})
   end

  manager
end

Obviously, that doesn't work but I'm a bit stuck at the moment.


Solution

  • I often separate such methods:

    def fetch_manager_rep_code_and_name
      rep_code_list.map do |rep_code|
        context = Finfolio::GetManagerByRepCode.call(rep_code: rep_code)
        { name: context.manager.response.first['Name'], rep_code: rep_code }
      end
    end
    
    def manager_rep_code_and_name
      @manager_rep_code_and_name ||= fetch_manager_rep_code_and_name
    end
    

    Usually, this also makes them easier to test.