1515require "view_component/translatable"
1616require "view_component/with_content_helper"
1717require "view_component/use_helpers"
18- require "view_component/cache_on"
1918
2019module ViewComponent
2120 class Base < ActionView ::Base
@@ -35,7 +34,6 @@ def config
3534 include ViewComponent ::Slotable
3635 include ViewComponent ::Translatable
3736 include ViewComponent ::WithContentHelper
38- include ViewComponent ::CacheOn
3937
4038 RESERVED_PARAMETER = :content
4139 VC_INTERNAL_DEFAULT_FORMAT = :html
@@ -52,6 +50,19 @@ def config
5250
5351 attr_accessor :__vc_original_view_context
5452
53+ # TODO
54+ #
55+ # @return [String]
56+ def cache_key
57+ if defined? ( __vc_cache_args )
58+ @vc_cache_key = Digest ::MD5 . hexdigest (
59+ __vc_cache_args . map { |method | send ( method ) } . join ( "-" )
60+ )
61+ else
62+ @vc_cache_key = nil
63+ end
64+ end
65+
5566 # Components render in their own view context. Helpers and other functionality
5667 # require a reference to the original Rails view context, an instance of
5768 # `ActionView::Base`. Use this method to set a reference to the original
@@ -119,11 +130,12 @@ def render_in(view_context, &block)
119130 end
120131 end . to_s
121132
122- # Avoid allocating new string when output_preamble and output_postamble are blank
123- if output_preamble . blank? && output_postamble . blank?
124- rendered_template
133+ if cache_key . present?
134+ Rails . cache . fetch ( @vc_cache_key ) do
135+ __vc_render_template ( rendered_template )
136+ end
125137 else
126- safe_output_preamble + rendered_template + safe_output_postamble
138+ __vc_render_template ( rendered_template )
127139 end
128140 else
129141 ""
@@ -321,6 +333,17 @@ def __vc_render_in_block_provided?
321333 defined? ( @view_context ) && @view_context && @__vc_render_in_block
322334 end
323335
336+
337+ # TODO
338+ def __vc_render_template ( rendered_template )
339+ # Avoid allocating new string when output_preamble and output_postamble are blank
340+ if output_preamble . blank? && output_postamble . blank?
341+ rendered_template
342+ else
343+ safe_output_preamble + rendered_template + safe_output_postamble
344+ end
345+ end
346+
324347 def __vc_content_set_by_with_content_defined?
325348 defined? ( @__vc_content_set_by_with_content )
326349 end
@@ -497,6 +520,14 @@ def sidecar_files(extensions)
497520 ( sidecar_files - [ source_location ] + sidecar_directory_files + nested_component_files ) . uniq
498521 end
499522
523+ def cache_on ( *args )
524+ class_eval <<~RUBY , __FILE__ , __LINE__ + 1
525+ def __vc_cache_args
526+ #{ args }
527+ end
528+ RUBY
529+ end
530+
500531 # Render a component for each element in a collection ([documentation](/guide/collections)):
501532 #
502533 # ```ruby
0 commit comments