Skip to content

Commit 3c31183

Browse files
authored
Add #current_template accessor and Template#path (#2283)
Prior to the compiler changes in v4, we set @current_template to be the current instance of the component. Now, we set it to the current ViewComponent::Template. In the GitHub monolith, we reference @current_template when doing certain diagnostic operations. I added an accessor to make this less messy to use (and test) and exposed #path on template, which now allows for such diagnostic operations to reference the specific component template being rendered.
1 parent 4620e7d commit 3c31183

File tree

6 files changed

+19
-1
lines changed

6 files changed

+19
-1
lines changed

docs/CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,10 @@ This release makes the following breaking changes:
136136

137137
*Joel Hawksley*
138138

139+
* Add `#current_template` accessor and `Template#path` for diagnostic usage.
140+
141+
*Joel Hawksley*
142+
139143
## 3.22.0
140144

141145
* Rewrite `ViewComponents at GitHub` documentation as more general `Best practices`.

lib/view_component/base.rb

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def config
5050
class_attribute :__vc_strip_trailing_whitespace, instance_accessor: false, instance_predicate: false, default: false
5151

5252
attr_accessor :__vc_original_view_context
53+
attr_reader :current_template
5354

5455
# Components render in their own view context. Helpers and other functionality
5556
# require a reference to the original Rails view context, an instance of

lib/view_component/template.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ class Template
77

88
DataWithSource = Struct.new(:format, :identifier, :short_identifier, :type, keyword_init: true)
99

10-
attr_reader :details
10+
attr_reader :details, :path
1111

1212
delegate :virtual_path, to: :@component
1313
delegate :format, :variant, to: :@details
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<%= current_template.path %>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# frozen_string_literal: true
2+
3+
class CurrentTemplateComponent < ViewComponent::Base
4+
end

test/sandbox/test/rendering_test.rb

+8
Original file line numberDiff line numberDiff line change
@@ -1270,4 +1270,12 @@ def test_render_anonymous_component_without_template
12701270
render_inline(mock_component.new)
12711271
end
12721272
end
1273+
1274+
def test_current_template
1275+
component = CurrentTemplateComponent.new
1276+
1277+
render_inline(component)
1278+
1279+
assert(rendered_content.include?("current_template_component.html.erb"))
1280+
end
12731281
end

0 commit comments

Comments
 (0)