File tree Expand file tree Collapse file tree 5 files changed +60
-0
lines changed Expand file tree Collapse file tree 5 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 1515require "view_component/translatable"
1616require "view_component/with_content_helper"
1717require "view_component/use_helpers"
18+ require "view_component/cache_on"
1819
1920module ViewComponent
2021 class Base < ActionView ::Base
@@ -34,6 +35,7 @@ def config
3435 include ViewComponent ::Slotable
3536 include ViewComponent ::Translatable
3637 include ViewComponent ::WithContentHelper
38+ include ViewComponent ::CacheOn
3739
3840 RESERVED_PARAMETER = :content
3941 VC_INTERNAL_DEFAULT_FORMAT = :html
Original file line number Diff line number Diff line change 1+ # frozen_string_literal: true
2+
3+ module ViewComponent ::CacheOn
4+ extend ActiveSupport ::Concern
5+
6+ included do
7+ def cache_key
8+ @vc_cache_args = vc_cache_args . map { |method | send ( method ) } if defined? ( vc_cache_args )
9+
10+ @vc_cache_key = Digest ::MD5 . hexdigest ( @vc_cache_args . join )
11+ end
12+ end
13+
14+ class_methods do
15+ def cache_on ( *args )
16+ define_method ( :vc_cache_args ) { args }
17+ end
18+
19+ def call
20+ if cache_key
21+ Rails . cache . fetch ( cache_key ) { super }
22+ else
23+ super
24+ end
25+ end
26+ end
27+ end
Original file line number Diff line number Diff line change 1+ < p class ='cache-component__cache-key '> <%= cache_key %> </ p >
2+ < p class ='cache-component__cache-message '> <%= "#{ foo } #{ bar } " %> </ p >
Original file line number Diff line number Diff line change 1+ # frozen_string_literal: true
2+
3+ class CacheComponent < ViewComponent ::Base
4+ cache_on :foo , :bar
5+
6+ attr_reader :foo , :bar
7+
8+ def initialize ( foo :, bar :)
9+ @foo = foo
10+ @bar = bar
11+ end
12+ end
Original file line number Diff line number Diff line change @@ -1215,4 +1215,21 @@ def test_with_format
12151215 assert_equal ( rendered_json [ "hello" ] , "world" )
12161216 end
12171217 end
1218+
1219+ def test_cache_component
1220+ component = CacheComponent . new ( foo : "foo" , bar : "bar" )
1221+ render_inline ( component )
1222+
1223+ assert_selector ( ".cache-component__cache-key" , text : component . cache_key )
1224+ assert_selector ( ".cache-component__cache-message" , text : "foo bar" )
1225+
1226+ render_inline ( CacheComponent . new ( foo : "foo" , bar : "bar" ) )
1227+
1228+ assert_selector ( ".cache-component__cache-key" , text : component . cache_key )
1229+
1230+ render_inline ( CacheComponent . new ( foo : "foo" , bar : "baz" ) )
1231+
1232+ refute_selector ( ".cache-component__cache-key" , text : component . cache_key )
1233+ refute_selector ( ".cache-component__cache-message" , text : "foo bar" )
1234+ end
12181235end
You can’t perform that action at this time.
0 commit comments