module RailsCacheIt module RelationExtension extend ActiveSupport::Concern included do alias_method_chain :to_a, :cache_it end def to_a_with_cache_it options = @_cache_it_options if options cache_name = to_sql blk = options.delete :blk if blk && (RailsCacheIt.cache_it[cache_name] != (new_result = blk.call)) RailsCacheIt.cache_it[cache_name] = new_result Rails.cache.delete cache_name end Rails.cache.fetch(cache_name, options) do self.to_a_without_cache_it end else self.to_a_without_cache_it end end def cache_it options = RailsCacheIt.default_options.dup, &blk options[:blk] = blk if blk @_cache_it_options = options self end end end