ruby-on-railsrubyperformancecachingdata-processing

How to "cache" the result of controller helper methods?


I'm using Ruby on Rails 7 and I've many helper_methods in my ApplicationController (see code below), some of which require relatively heavy data processing to execute e.g. because they check complex parameter input data for security reasons.

class ApplicationController < ActionController::Base
  helper_method :param_heavy_processing
  helper_method :param_medium_processing
  helper_method :param_light_processing
  // ...

  private

  def param_heavy_processing
    return nil unless params[:param_heavy].present?
    // heavy data processing e.g. many iterations
  end

  def param_medium_processing
    return nil unless params[:param_medium].present?
    // medium data processing
  end

  def param_light_processing
    return nil unless params[:param_light].present?
    // light data processing
  end

 // ...
end

In my views and controllers I call these methods sparingly, in many cases more than once in a request flow. By logging into them, it seems that each time I call a helper method then data processing for that method is performed by scratch (again and again, once per call), which is not good for performance on the long run.

So, I thought to "cache" someway the result of the first call of these methods for the entire controller action flow in order to execute data processing only once per request. Is it possible? If so, how?


Solution

  • Here is alternative pattern you can use for the current request. Heavy processing executes at most one time per current request even if the result returns nil.

    def param_heavy_processing
      return if params[:param_heavy].blank?
      
      return @param_heavy_processing if defined? @param_heavy_processing
      @param_heavy_processing = # heavy data processing
    end