view_component 4.15.0 → 4.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9da4df780e2f53937b1593ef29fbbf9ce09662b48de7bc56ceae812c43880d2f
4
- data.tar.gz: 94c6f23684dc139431a5c912a9e7fab5f70e2e794ba6bb72f5b66211c97f0e8c
3
+ metadata.gz: 04ae333990353bff3c4671c78db517fbe53ddcb15d9bfeb4448bc2d52c710f5b
4
+ data.tar.gz: ef958403f0326485a5f2035a9d744c878197c041247df3f76e68cf2712b9a652
5
5
  SHA512:
6
- metadata.gz: 50b36d70558457271f43deb0b67473209af190979ca48c68ce1b3116b27abf06255b0d9312c53382600be23d75aa2304b58926d9e52f314923c4968182b10e53
7
- data.tar.gz: c687e6eec0d97bd5ea53b3f5b51012e94ca75bd3d659bd1ac2ea03d3343e4d88e695aa5b822d5fe8f55a4a239163cd3df7048a33195b95132ac95e186a491b7b
6
+ metadata.gz: 68e6ae32b57a9c1323ed64eb82c866e9595f2aeca16009b532f4922e85abe72536b06dc61d75328a202faef438f57e4d9deebef8ace06c96a3c7d609ad946a38
7
+ data.tar.gz: 52ef898174f4270dbc4bdcc91c0d841d35fe12c04c8b46e0639b0b1cb1a43b2789d24174cf70f2bc4ee3718eae536448b24833247cdd9a0f891c33678186060f
@@ -0,0 +1 @@
1
+ <%= render MultipartMailerComponent.new %>
@@ -0,0 +1 @@
1
+ <%= render MultipartMailerComponent.new %>
data/docs/CHANGELOG.md CHANGED
@@ -10,6 +10,130 @@ nav_order: 6
10
10
 
11
11
  ## main
12
12
 
13
+ ## 4.20.0
14
+
15
+ * Fix `invalid byte sequence in UTF-8` errors when precomputing cache digests for components loaded from encrypted or binary source files.
16
+
17
+ *Joel Junström*
18
+
19
+ * Fix cache digests missing components rendered through a slot declared with the component's class, through a method or variable that holds the component, or through a module the component includes. Any constant naming a component in a component's Ruby or templates now counts as a dependency, and included modules are digested like superclasses.
20
+
21
+ *Erik Axel Nielsen*
22
+
23
+ * Add an informational CI check that runs added and modified tests without a pull request's implementation changes to identify regression coverage.
24
+
25
+ *Joel Hawksley*
26
+
27
+ * Speed up rendering with direct compiled-template calls and avoid intermediate method allocations when invoking lambda-backed slots.
28
+
29
+ *Joel Hawksley*
30
+
31
+ * Fix `Couldn't find template for digesting` errors when computing cache digests for templates that render components. Action View inferred a partial from `render SomeComponent.new`, so partials inferred from component renders are now discarded. Component renders are found with Prism rather than a regular expression, adding a dependency on the `prism` gem.
32
+
33
+ *Joel Hawksley*
34
+
35
+ * Fix components rendering the template for the first format a lookup context rendered in, instead of the current one. An Action Mailer email that declares `format.text` before `format.html` rendered the text template of each component into its HTML part. Components now reuse the details key Action View memoizes, which Action View resets whenever a detail such as `formats` changes. Regression from 4.16.0.
36
+
37
+ *Jan Schilbach*
38
+
39
+ * Look up each component's sidecar templates and translations once while eager loading, instead of again when it compiles, loads its translations, and computes its cache digest, and for each of its subclasses. Time spent in ViewComponent during the boot benchmark drops by about a quarter.
40
+
41
+ *Clément Joubert*
42
+
43
+ * Measure cache digest precomputation in the boot benchmark by disabling class reloading in the benchmark app and having each generated component render another.
44
+
45
+ *Joel Hawksley*
46
+
47
+ * Add a CI performance check that fails a pull request when any benchmark scenario's component/partial render-time ratio, or ViewComponent's share of app boot time, regresses by more than 5% against the base branch on Rails 8.1 or Rails main.
48
+
49
+ *Joel Hawksley*
50
+
51
+ * Fail the test suite when a gem in the Gemfile or gemspec isn't loaded.
52
+
53
+ *Joel Hawksley*
54
+
55
+ * Remove the unused `selenium-webdriver` and `tailwindcss-rails` development dependencies.
56
+
57
+ *Joel Hawksley*
58
+
59
+ * Speed up `sidecar_files`, which 4.18's cache digest precomputation calls for every component and superclass at boot, by globbing each directory once instead of once per extension. On an app with 302 components, `compile.view_component` drops from 2.3 s to 1.2 s.
60
+
61
+ *Clément Joubert*
62
+
63
+ ## 4.19.0
64
+
65
+ * Remove the unused `concurrent-ruby` dependency. `require "concurrent-ruby"` loaded every concurrent-ruby class at boot, a leftover from the `Concurrent::ReadWriteLock` the compiler no longer uses.
66
+
67
+ *Clément Joubert*
68
+
69
+ * Fix every request raising `NoMethodError` in development when an autoload path is a `Pathname`, as engines such as Madmin add. The template watcher now passes the autoload paths to the file watcher as strings.
70
+
71
+ *Anthony Veaudry*
72
+
73
+ * Fix the template annotations integration test failing when it ran after the coverage compile tests, which left components compiled without the annotation in the test cache.
74
+
75
+ *Anthony Veaudry*
76
+
77
+ ## 4.18.0
78
+
79
+ * Enable caching support for all components by default, and rename `ViewComponent::ExperimentallyCacheable` to `ViewComponent::Cacheable`. Including the module is no longer necessary. Breaking: remove existing `include ViewComponent::ExperimentallyCacheable` lines. Caching is no longer experimental.
80
+
81
+ *Erik Axel Nielsen, Joel Hawksley*
82
+
83
+ ## 4.17.0
84
+
85
+ * Only register the executor hook that watches component templates when Action View doesn't cache templates at boot. With template caching on, as in production, the hook did nothing but still read `ActionView::Base.cache_template_loading` on every request. That value lives in a class variable, which non-main Ractors can't read on Ruby 4.0, so under Rails' experimental `Rails.application.ractorize!` every request failed.
86
+
87
+ *Mikael Henriksson*
88
+
89
+ * Fix `Component.translate` raising `UncaughtThrowError` for keys missing from the sidecar translations, and `NoMethodError` for components without sidecar translations. It now falls back to the global translations, like the instance method does. Fix `translate` returning the `default:` value instead of an existing global translation.
90
+
91
+ *Andrii Furmanets*
92
+
93
+ * Only recompile components when a template or a translation file changed, instead of before every request, when templates aren't cached. Pages render about twice as fast in development.
94
+
95
+ *Clément Joubert*
96
+
97
+ ## 4.16.0
98
+
99
+ * Fix subclasses defined after their parent renders a collection using the parent's default collection parameter name instead of their own. Fix recompiling a component not refreshing its collection parameter, counter, and iteration detection. Compute that detection when a component compiles, and store the results frozen so they're shareable across Ractors.
100
+
101
+ *Ben Sheldon*
102
+
103
+ * Fix collection counter and iteration detection, and collection and reserved parameter validation, when `initialize` arguments are forwarded through anonymous arguments (`...` or `**`), such as by prepended modules and subclasses calling `super`.
104
+
105
+ *Ben Sheldon*
106
+
107
+ * Update development and documentation dependencies, baseline existing Audition findings, and accommodate updated lint rules.
108
+
109
+ *Joel Hawksley*
110
+
111
+ * Invalidate Action View's memoized template digests when a component registers with `ViewComponent::CacheDigest`, so a digest computed before the component loaded isn't served for the rest of the process.
112
+
113
+ *Erik Axel Nielsen*
114
+
115
+ * Raise errors encountered while computing a component's cache digest instead of degrading to an untracked component that can serve stale fragments.
116
+
117
+ *Erik Axel Nielsen*
118
+
119
+ * Give `<% cache %>` blocks inside a component's own template a digest, for components that `include ViewComponent::ExperimentallyCacheable`.
120
+
121
+ Rails digests the virtual path of whichever template is rendering. Inside a component that path resolves to no template, because component templates aren't in the view paths, so the Digestor returned an empty digest and the fragment was never invalidated. The only signal was a `Couldn't find template for digesting` line in the log. 4.15.0 fixed the case where the `cache` block wraps the component in a view. This fixes the case where the block sits in the component's template.
122
+
123
+ *Erik Axel Nielsen*
124
+
125
+ * Fix line numbers and, under coverage, missing output for ERB templates that Rails doesn't annotate.
126
+
127
+ On Rails 8.1+, ViewComponent compensated for the newline Rails adds to compiled ERB output ([rails/rails#53731](https://github.com/rails/rails/pull/53731)) for every ERB template, whether from a file or from `erb_template`. That newline lives inside the `<!-- BEGIN ... -->` annotation, which Rails only emits when `annotate_rendered_view_with_filenames` is enabled *and* the template's format is HTML. Compensating unconditionally shifted backtraces for non-HTML templates (`.text.erb`, `.css.erb`) and for every ERB template when annotations are disabled, such as in production, by one line. When coverage was running, the same mismatch made the annotation-stripping workaround remove real template source, so non-HTML templates rendered empty.
128
+
129
+ Inline templates now decide the compensation when they compile rather than when the component class is defined, matching file templates.
130
+
131
+ *Ryutaro Mizokami*
132
+
133
+ * Reduce per-render allocations. Inline renders drop 2 to 3 allocations and collection renders drop 4 to 8 depending on Rails/Ruby version by caching the instrumentation-enabled flag at the module level, memoizing the empty-details `Requested` per `LookupContext`, hoisting per-item metadata lookups out of the collection render loop, and dropping a few gratuitous `**` splats on the `Collection` API boundary.
134
+
135
+ *Joel Hawksley*
136
+
13
137
  ## 4.15.0
14
138
 
15
139
  * Add experimental caching support, opt-in per component via `include ViewComponent::ExperimentallyCacheable`.
@@ -3,10 +3,12 @@
3
3
  require "action_view"
4
4
  require "action_view/base"
5
5
  require "view_component/collection"
6
+ require "view_component/cache_digest"
6
7
  require "view_component/compile_cache"
7
8
  require "view_component/compiler"
8
9
  require "view_component/config"
9
10
  require "view_component/errors"
11
+ require "view_component/cacheable"
10
12
  require "view_component/inline_template"
11
13
  require "view_component/preview"
12
14
  require "view_component/request_details"
@@ -31,6 +33,20 @@ end
31
33
  module ViewComponent
32
34
  class Base
33
35
  class << self
36
+ # A digest of the component's source, ancestors, and rendered dependencies.
37
+ #
38
+ # @param finder [ActionView::LookupContext, nil]
39
+ # @param format [Symbol]
40
+ #
41
+ # @return [String]
42
+ def cache_digest(finder: nil, format: :html)
43
+ ViewComponent::CacheDigest.digest(
44
+ self,
45
+ finder: finder || ViewComponent::CacheDigest.default_finder,
46
+ format: format
47
+ )
48
+ end
49
+
34
50
  delegate(*ViewComponent::Config.defaults.keys, to: :config)
35
51
 
36
52
  # Returns the current config.
@@ -106,6 +122,10 @@ module ViewComponent
106
122
  def render_in(view_context, **, &block)
107
123
  self.class.__vc_compile(raise_errors: true) unless self.class.__vc_compiled?
108
124
 
125
+ if self.class.__vc_cache_output && !@__vc_cache_bypassed
126
+ return __vc_render_cached(view_context, block)
127
+ end
128
+
109
129
  __vc_check_reused_instance!
110
130
  __vc_reset_render_state!
111
131
 
@@ -423,6 +443,21 @@ module ViewComponent
423
443
  @view_context.instance_variable_set(:@virtual_path, old_virtual_path)
424
444
  end
425
445
 
446
+ # Use the component's source digest for fragments inside its own template.
447
+ #
448
+ # @private
449
+ def digest_path_from_template(template)
450
+ component_path = self.class.virtual_path
451
+ return super unless component_path && template.virtual_path == component_path
452
+
453
+ digest = self.class.cache_digest(
454
+ finder: lookup_context,
455
+ format: template.format || lookup_context.formats.first || :html
456
+ )
457
+
458
+ digest.present? ? "#{component_path}:#{digest}" : component_path
459
+ end
460
+
426
461
  private
427
462
 
428
463
  attr_reader :view_context
@@ -589,7 +624,10 @@ module ViewComponent
589
624
  return [] unless identifier
590
625
  return [] unless name
591
626
 
592
- extensions = extensions.join(",")
627
+ # One glob per directory, filtered by extension, rather than a brace
628
+ # pattern per extension: Dir expands braces into one directory listing
629
+ # per extension.
630
+ extensions = extensions.map(&:to_s)
593
631
 
594
632
  # view files in a directory named like the component
595
633
  directory = File.dirname(identifier)
@@ -608,19 +646,29 @@ module ViewComponent
608
646
  # Without this, `MyOtherComponent` will not look for `my_component/my_other_component.html.erb`
609
647
  nested_component_files =
610
648
  if name.include?("::") && component_name != filename
611
- Dir["#{directory}/#{filename}/#{component_name}.*{#{extensions}}"]
649
+ __vc_files_ending_with(extensions, "#{directory}/#{filename}/#{component_name}.*")
612
650
  else
613
651
  []
614
652
  end
615
653
 
616
654
  # view files in the same directory as the component
617
- sidecar_files = Dir["#{directory}/#{component_name}.*{#{extensions}}"]
655
+ sidecar_files = __vc_files_ending_with(extensions, "#{directory}/#{component_name}.*")
618
656
 
619
- sidecar_directory_files = Dir["#{directory}/#{component_name}/#{filename}.*{#{extensions}}"]
657
+ sidecar_directory_files = __vc_files_ending_with(extensions, "#{directory}/#{component_name}/#{filename}.*")
620
658
 
621
659
  (sidecar_files - [identifier] + sidecar_directory_files + nested_component_files).uniq
622
660
  end
623
661
 
662
+ # `sidecar_files`, looked up once per component while eager loading:
663
+ # every component looks up its superclasses' templates and translations
664
+ # too, when it compiles, loads its translations, and computes its cache
665
+ # digest.
666
+ #
667
+ # @private
668
+ def __vc_sidecar_files(extensions)
669
+ CompileCache.sidecar_files_for(self, extensions) { sidecar_files(extensions) }
670
+ end
671
+
624
672
  # Render a component for each element in a collection ([documentation](/guide/collections)):
625
673
  #
626
674
  # ```ruby
@@ -631,7 +679,7 @@ module ViewComponent
631
679
  # @param spacer_component [ViewComponent::Base] Component instance to be rendered between items.
632
680
  # @param args [Arguments] Arguments to pass to the ViewComponent every time.
633
681
  def with_collection(collection, spacer_component: nil, **args)
634
- Collection.new(self, collection, spacer_component, **args)
682
+ Collection.new(self, collection, spacer_component, args)
635
683
  end
636
684
 
637
685
  # @private
@@ -668,6 +716,7 @@ module ViewComponent
668
716
  # owner is included in a prefix like `ApplicationComponent.inherited`.
669
717
  child.identifier = caller_locations(1, 10).reject { |l| l.base_label == "inherited" }[0].path
670
718
  child.virtual_path = child.name&.underscore
719
+ ViewComponent::CacheDigest.register(child)
671
720
 
672
721
  # Set collection parameter to the extended component
673
722
  child.with_collection_parameter(__vc_provided_collection_parameter)
@@ -707,6 +756,17 @@ module ViewComponent
707
756
  @__vc_compiler ||= Compiler.new(self)
708
757
  end
709
758
 
759
+ # Synthetic digest source computed at boot. Not inherited, since each
760
+ # component's source differs.
761
+ #
762
+ # @private
763
+ attr_accessor :__vc_cache_digest_source
764
+
765
+ # @private
766
+ def __vc_template_formats
767
+ __vc_compiler.template_formats
768
+ end
769
+
710
770
  # Set the parameter name used when rendering elements of a collection ([documentation](/guide/collections)):
711
771
  #
712
772
  # ```ruby
@@ -716,7 +776,7 @@ module ViewComponent
716
776
  # @param parameter [Symbol] The parameter name used when rendering elements of a collection.
717
777
  def with_collection_parameter(parameter)
718
778
  @__vc_provided_collection_parameter = parameter
719
- @__vc_initialize_parameters = nil
779
+ @__vc_collection_arguments = nil
720
780
  end
721
781
 
722
782
  # Strips trailing whitespace from templates before compiling them.
@@ -746,10 +806,14 @@ module ViewComponent
746
806
  # rendering is optional.
747
807
  # @private
748
808
  def __vc_validate_collection_parameter!(validate_default: false)
749
- parameter = validate_default ? __vc_collection_parameter : __vc_provided_collection_parameter
809
+ if validate_default
810
+ return if __vc_collection_arguments[:parameter_accepted]
750
811
 
751
- return unless parameter
752
- return if __vc_initialize_parameter_names.include?(parameter) || __vc_splatted_keyword_argument_present?
812
+ raise MissingCollectionArgumentError.new(name, __vc_collection_parameter)
813
+ end
814
+
815
+ parameter = __vc_provided_collection_parameter
816
+ return if __vc_collection_parameter_accepted?(parameter)
753
817
 
754
818
  raise MissingCollectionArgumentError.new(name, parameter)
755
819
  end
@@ -766,53 +830,100 @@ module ViewComponent
766
830
 
767
831
  # @private
768
832
  def __vc_collection_parameter
769
- @__vc_provided_collection_parameter ||= name && name.demodulize.underscore.chomp("_component").to_sym
833
+ __vc_collection_arguments[:parameter]
770
834
  end
771
835
 
772
836
  # @private
773
837
  def __vc_collection_counter_parameter
774
- @__vc_collection_counter_parameter ||= :"#{__vc_collection_parameter}_counter"
838
+ __vc_collection_arguments[:counter_parameter]
775
839
  end
776
840
 
777
841
  # @private
778
842
  def __vc_counter_argument_present?
779
- __vc_initialize_parameter_names.include?(__vc_collection_counter_parameter)
843
+ __vc_collection_arguments[:counter]
780
844
  end
781
845
 
782
846
  # @private
783
847
  def __vc_collection_iteration_parameter
784
- @__vc_collection_iteration_parameter ||= :"#{__vc_collection_parameter}_iteration"
848
+ __vc_collection_arguments[:iteration_parameter]
785
849
  end
786
850
 
787
851
  # @private
788
852
  def __vc_iteration_argument_present?
789
- __vc_initialize_parameter_names.include?(__vc_collection_iteration_parameter)
853
+ __vc_collection_arguments[:iteration]
854
+ end
855
+
856
+ # @private
857
+ def __vc_build_collection_arguments
858
+ names =
859
+ if respond_to?(:attribute_names)
860
+ attribute_names.map(&:to_sym)
861
+ else
862
+ __vc_initialize_signatures.flat_map { |_owner, parameters| parameters.map(&:last) }
863
+ end
864
+ parameter = __vc_provided_collection_parameter || (name && name.demodulize.underscore.chomp("_component").to_sym)
865
+ counter_parameter = :"#{parameter}_counter"
866
+ iteration_parameter = :"#{parameter}_iteration"
867
+
868
+ @__vc_collection_arguments = Ractor.make_shareable(
869
+ {
870
+ initialize_parameter_names: names,
871
+ parameter: parameter,
872
+ parameter_accepted: parameter.nil? || names.include?(parameter) || __vc_splatted_keyword_argument_present?,
873
+ counter_parameter: counter_parameter,
874
+ counter: names.include?(counter_parameter),
875
+ iteration_parameter: iteration_parameter,
876
+ iteration: names.include?(iteration_parameter)
877
+ }
878
+ )
790
879
  end
791
880
 
792
881
  private
793
882
 
883
+ def __vc_collection_arguments
884
+ @__vc_collection_arguments || __vc_build_collection_arguments
885
+ end
886
+
887
+ def __vc_collection_parameter_accepted?(parameter)
888
+ parameter.nil? || __vc_initialize_parameter_names.include?(parameter) || __vc_splatted_keyword_argument_present?
889
+ end
890
+
794
891
  def __vc_splatted_keyword_argument_present?
795
- __vc_initialize_parameters.flatten.include?(:keyrest)
892
+ prepended_modules = ancestors.grep(Class).flat_map { |klass| klass.ancestors.take_while { |mod| mod != klass } }
893
+
894
+ __vc_initialize_signatures.any? do |owner, parameters|
895
+ parameters.any? do |type, name|
896
+ type == :keyrest && (name != :** || !prepended_modules.include?(owner))
897
+ end
898
+ end
796
899
  end
797
900
 
798
901
  def __vc_initialize_parameter_names
799
- @__vc_initialize_parameter_names ||=
800
- if respond_to?(:attribute_names)
801
- attribute_names.map(&:to_sym)
802
- else
803
- __vc_initialize_parameters.map(&:last)
804
- end
902
+ __vc_collection_arguments[:initialize_parameter_names]
805
903
  end
806
904
 
807
- def __vc_initialize_parameters
808
- @__vc_initialize_parameters ||= instance_method(:initialize).parameters
905
+ def __vc_initialize_signatures
906
+ signatures = []
907
+ method = instance_method(:initialize)
908
+ while method
909
+ signatures << [method.owner, method.parameters]
910
+ break unless method.parameters.any? { |type, _| type == :keyrest }
911
+
912
+ method = method.super_method
913
+ end
914
+ signatures
809
915
  end
810
916
 
811
- def __vc_provided_collection_parameter
812
- @__vc_provided_collection_parameter ||= nil
917
+ def __vc_files_ending_with(extensions, pattern)
918
+ paths = Dir[pattern]
919
+ extensions.flat_map { |extension| paths.select { |path| path.end_with?(extension) } }
813
920
  end
921
+
922
+ attr_reader :__vc_provided_collection_parameter
814
923
  end
815
924
 
925
+ include ViewComponent::Cacheable
926
+
816
927
  ActiveSupport.run_load_hooks(:view_component, self)
817
928
  end
818
929
  end
@@ -26,12 +26,15 @@ module ViewComponent
26
26
  dependencies = dependencies - [declared] + [virtual_path]
27
27
  end
28
28
 
29
- dependencies + CacheDigest.dependencies_in(template)
30
- rescue
31
- # A broken digest is preferable to a broken render. Falling back to the
32
- # dependencies Rails found on its own means the component simply isn't
33
- # tracked, which is the pre-existing behavior.
34
- super
29
+ # Swap the partials Action View wrongly infers from component renders,
30
+ # such as `news/new` from `render ChildComponent.new`, for the
31
+ # components themselves.
32
+ return dependencies unless CacheDigest::CONSTANT_RENDER.match?(source)
33
+
34
+ component_paths, inferred_partials =
35
+ CacheDigest.component_renders_in(CacheDigest.compiled_source(template), name)
36
+
37
+ (dependencies - inferred_partials + component_paths).uniq
35
38
  end
36
39
 
37
40
  # @private
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_view/digestor"
4
+
5
+ module ViewComponent
6
+ module CacheDigest
7
+ # Lets `ActionView::Digestor` find the synthetic templates `Resolver` builds.
8
+ #
9
+ # Prepended to the Digestor's singleton class rather than appending
10
+ # `Resolver` to the application's view paths, so the resolver is only ever
11
+ # consulted while digesting. Code that walks `view_paths` and expects every
12
+ # entry to be a file system resolver is unaffected.
13
+ #
14
+ # @private
15
+ module DigestorLookup
16
+ # @private
17
+ def self.install!
18
+ digestor = ActionView::Digestor.singleton_class
19
+ return if digestor.include?(self)
20
+
21
+ digestor.prepend(self)
22
+ end
23
+
24
+ private
25
+
26
+ def find_template(finder, name, prefixes, partial, keys)
27
+ Resolver.instance.find_templates(name, prefixes.first, partial, {formats: finder.formats}).first || super
28
+ end
29
+ end
30
+ end
31
+ end