File tree 5 files changed +60
-0
lines changed
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 @@ -1215,4 +1215,21 @@ def test_with_format
1215
1215
assert_equal ( rendered_json [ "hello" ] , "world" )
1216
1216
end
1217
1217
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
1218
1235
end
You can’t perform that action at this time.
0 commit comments