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 15
15
require "view_component/translatable"
16
16
require "view_component/with_content_helper"
17
17
require "view_component/use_helpers"
18
+ require "view_component/cache_on"
18
19
19
20
module ViewComponent
20
21
class Base < ActionView ::Base
@@ -34,6 +35,7 @@ def config
34
35
include ViewComponent ::Slotable
35
36
include ViewComponent ::Translatable
36
37
include ViewComponent ::WithContentHelper
38
+ include ViewComponent ::CacheOn
37
39
38
40
RESERVED_PARAMETER = :content
39
41
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 @@ -1240,4 +1240,21 @@ def test_request_param
1240
1240
1241
1241
assert_text ( "foo" )
1242
1242
end
1243
+
1244
+ def test_cache_component
1245
+ component = CacheComponent . new ( foo : "foo" , bar : "bar" )
1246
+ render_inline ( component )
1247
+
1248
+ assert_selector ( ".cache-component__cache-key" , text : component . cache_key )
1249
+ assert_selector ( ".cache-component__cache-message" , text : "foo bar" )
1250
+
1251
+ render_inline ( CacheComponent . new ( foo : "foo" , bar : "bar" ) )
1252
+
1253
+ assert_selector ( ".cache-component__cache-key" , text : component . cache_key )
1254
+
1255
+ render_inline ( CacheComponent . new ( foo : "foo" , bar : "baz" ) )
1256
+
1257
+ refute_selector ( ".cache-component__cache-key" , text : component . cache_key )
1258
+ refute_selector ( ".cache-component__cache-message" , text : "foo bar" )
1259
+ end
1243
1260
end
You can’t perform that action at this time.
0 commit comments