/
base.rb
434 lines (345 loc) · 14.1 KB
/
base.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# frozen_string_literal: true
require "action_view"
require "active_support/configurable"
require "view_component/collection"
require "view_component/previewable"
module ViewComponent
class Base < ActionView::Base
include ActiveSupport::Configurable
include ViewComponent::Previewable
# For CSRF authenticity tokens in forms
delegate :form_authenticity_token, :protect_against_forgery?, to: :helpers
class_attribute :content_areas
self.content_areas = [] # class_attribute:default doesn't work until Rails 5.2
# Entrypoint for rendering components.
#
# view_context: ActionView context from calling view
# block: optional block to be captured within the view context
#
# returns HTML that has been escaped by the respective template handler
#
# Example subclass:
#
# app/components/my_component.rb:
# class MyComponent < ViewComponent::Base
# def initialize(title:)
# @title = title
# end
# end
#
# app/components/my_component.html.erb
# <span title="<%= @title %>">Hello, <%= content %>!</span>
#
# In use:
# <%= render MyComponent.new(title: "greeting") do %>world<% end %>
# returns:
# <span title="greeting">Hello, world!</span>
#
def render_in(view_context, &block)
self.class.compile(raise_errors: true)
@view_context = view_context
@lookup_context ||= view_context.lookup_context
# required for path helpers in older Rails versions
@view_renderer ||= view_context.view_renderer
# For content_for
@view_flow ||= view_context.view_flow
# For i18n
@virtual_path ||= virtual_path
# For template variants (+phone, +desktop, etc.)
@variant = @lookup_context.variants.first
# For caching, such as #cache_if
@current_template = nil unless defined?(@current_template)
old_current_template = @current_template
@current_template = self
# Assign captured content passed to component as a block to @content
@content = view_context.capture(self, &block) if block_given?
before_render
if render?
send(self.class.call_method_name(@variant))
else
""
end
ensure
@current_template = old_current_template
end
def before_render
before_render_check
end
def before_render_check
# noop
end
def render?
true
end
def initialize(*); end
# If trying to render a partial or template inside a component,
# pass the render call to the parent view_context.
def render(options = {}, args = {}, &block)
if options.is_a?(String) || (options.is_a?(Hash) && options.has_key?(:partial))
view_context.render(options, args, &block)
else
super
end
end
def controller
@controller ||= view_context.controller
end
# Provides a proxy to access helper methods
def helpers
@helpers ||= view_context
end
# Removes the first part of the path and the extension.
def virtual_path
self.class.source_location.gsub(%r{(.*app/components)|(\.rb)}, "")
end
# For caching, such as #cache_if
def view_cache_dependencies
[]
end
# For caching, such as #cache_if
def format
@variant
end
# Assign the provided content to the content area accessor
def with(area, content = nil, &block)
unless content_areas.include?(area)
raise ArgumentError.new "Unknown content_area '#{area}' - expected one of '#{content_areas}'"
end
if block_given?
content = view_context.capture(&block)
end
instance_variable_set("@#{area}".to_sym, content)
nil
end
private
# Exposes the current request to the component.
# Use sparingly as doing so introduces coupling
# that inhibits encapsulation & reuse.
def request
@request ||= controller.request
end
attr_reader :content, :view_context
# The controller used for testing components.
# Defaults to ApplicationController. This should be set early
# in the initialization process and should be set to a string.
mattr_accessor :test_controller
@@test_controller = "ApplicationController"
class << self
attr_accessor :source_location
# Render a component collection.
def with_collection(*args)
Collection.new(self, *args)
end
# Provide identifier for ActionView template annotations
def short_identifier
@short_identifier ||= defined?(Rails.root) ? source_location.sub("#{Rails.root}/", "") : source_location
end
def inherited(child)
# If we're in Rails, add application url_helpers to the component context
if defined?(Rails)
child.include Rails.application.routes.url_helpers unless child < Rails.application.routes.url_helpers
end
# Derive the source location of the component Ruby file from the call stack.
# We need to ignore `inherited` frames here as they indicate that `inherited`
# has been re-defined by the consuming application, likely in ApplicationComponent.
child.source_location = caller_locations(1, 10).reject { |l| l.label == "inherited" }[0].absolute_path
super
end
def call_method_name(variant)
if variant.present? && variants.include?(variant)
"call_#{variant}"
else
"call"
end
end
def compiled?
@compiled ||= false
@compiled && ActionView::Base.cache_template_loading
end
# Compile templates to instance methods, assuming they haven't been compiled already.
#
# Do as much work as possible in this step, as doing so reduces the amount
# of work done each time a component is rendered.
def compile(raise_errors: false)
return if compiled?
if template_errors.present?
raise ViewComponent::TemplateError.new(template_errors) if raise_errors
return false
end
if instance_methods(false).include?(:before_render_check)
ActiveSupport::Deprecation.warn(
"`before_render_check` will be removed in v3.0.0. Use `before_render` instead."
)
end
# Remove any existing singleton methods,
# as Ruby warns when redefining a method.
remove_possible_singleton_method(:variants)
remove_possible_singleton_method(:collection_parameter)
remove_possible_singleton_method(:collection_counter_parameter)
remove_possible_singleton_method(:counter_argument_present?)
define_singleton_method(:variants) do
templates.map { |template| template[:variant] } + variants_from_inline_calls(inline_calls)
end
define_singleton_method(:collection_parameter) do
if provided_collection_parameter
provided_collection_parameter
else
name.demodulize.underscore.chomp("_component").to_sym
end
end
define_singleton_method(:collection_counter_parameter) do
"#{collection_parameter}_counter".to_sym
end
define_singleton_method(:counter_argument_present?) do
instance_method(:initialize).parameters.map(&:second).include?(collection_counter_parameter)
end
validate_collection_parameter! if raise_errors
# If template name annotations are turned on, a line is dynamically
# added with a comment. In this case, we want to return a different
# starting line number so errors that are raised will point to the
# correct line in the component template.
line_number =
if ActionView::Base.respond_to?(:annotate_rendered_view_with_filenames) &&
ActionView::Base.annotate_rendered_view_with_filenames
-2
else
-1
end
templates.each do |template|
# Remove existing compiled template methods,
# as Ruby warns when redefining a method.
method_name = call_method_name(template[:variant])
undef_method(method_name.to_sym) if instance_methods.include?(method_name.to_sym)
class_eval <<-RUBY, template[:path], line_number
def #{method_name}
@output_buffer = ActionView::OutputBuffer.new
#{compiled_template(template[:path])}
end
RUBY
end
@compiled = true
end
# we'll eventually want to update this to support other types
def type
"text/html"
end
def format
:html
end
def identifier
source_location
end
def with_content_areas(*areas)
if areas.include?(:content)
raise ArgumentError.new ":content is a reserved content area name. Please use another name, such as ':body'"
end
attr_reader(*areas)
self.content_areas = areas
end
# Support overriding collection parameter name
def with_collection_parameter(param)
@provided_collection_parameter = param
end
# Ensure the component initializer accepts the
# collection parameter. By default, we do not
# validate that the default parameter name
# is accepted, as support for collection
# rendering is optional.
def validate_collection_parameter!(validate_default: false)
parameter = validate_default ? collection_parameter : provided_collection_parameter
return unless parameter
return if instance_method(:initialize).parameters.map(&:last).include?(parameter)
raise ArgumentError.new(
"#{self} initializer must accept " \
"`#{parameter}` collection parameter."
)
end
private
def provided_collection_parameter
@provided_collection_parameter ||= nil
end
def compiled_template(file_path)
handler = ActionView::Template.handler_for_extension(File.extname(file_path).gsub(".", ""))
template = File.read(file_path)
if handler.method(:call).parameters.length > 1
handler.call(self, template)
else
handler.call(OpenStruct.new(source: template, identifier: identifier, type: type))
end
end
def inline_calls
@inline_calls ||=
begin
# Fetch only ViewComponent ancestor classes to limit the scope of
# finding inline calls
view_component_ancestors =
ancestors.take_while { |ancestor| ancestor != ViewComponent::Base } - included_modules
view_component_ancestors.flat_map { |ancestor| ancestor.instance_methods(false).grep(/^call/) }.uniq
end
end
def inline_calls_defined_on_self
@inline_calls_defined_on_self ||= instance_methods(false).grep(/^call/)
end
def matching_views_in_source_location
return [] unless source_location
location_without_extension = source_location.chomp(File.extname(source_location))
extenstions = ActionView::Template.template_handler_extensions.join(",")
# view files in the same directory as te component
sidecar_files = Dir["#{location_without_extension}.*{#{extenstions}}"]
# view files in a directory named like the component
directory = File.dirname(source_location)
filename = File.basename(source_location, ".rb")
component_name = name.demodulize.underscore
sidecar_directory_files = Dir["#{directory}/#{component_name}/#{filename}.*{#{extenstions}}"]
(sidecar_files - [source_location] + sidecar_directory_files)
end
def templates
@templates ||=
matching_views_in_source_location.each_with_object([]) do |path, memo|
pieces = File.basename(path).split(".")
memo << {
path: path,
variant: pieces.second.split("+").second&.to_sym,
handler: pieces.last
}
end
end
def template_errors
@template_errors ||=
begin
errors = []
if (templates + inline_calls).empty?
errors << "Could not find a template file or inline render method for #{self}."
end
if templates.count { |template| template[:variant].nil? } > 1
errors << "More than one template found for #{self}. There can only be one default template file per component."
end
invalid_variants = templates
.group_by { |template| template[:variant] }
.map { |variant, grouped| variant if grouped.length > 1 }
.compact
.sort
unless invalid_variants.empty?
errors << "More than one template found for #{'variant'.pluralize(invalid_variants.count)} #{invalid_variants.map { |v| "'#{v}'" }.to_sentence} in #{self}. There can only be one template file per variant."
end
if templates.find { |template| template[:variant].nil? } && inline_calls_defined_on_self.include?(:call)
errors << "Template file and inline render method found for #{self}. There can only be a template file or inline render method per component."
end
duplicate_template_file_and_inline_variant_calls =
templates.pluck(:variant) & variants_from_inline_calls(inline_calls_defined_on_self)
unless duplicate_template_file_and_inline_variant_calls.empty?
count = duplicate_template_file_and_inline_variant_calls.count
errors << "Template #{'file'.pluralize(count)} and inline render #{'method'.pluralize(count)} found for #{'variant'.pluralize(count)} #{duplicate_template_file_and_inline_variant_calls.map { |v| "'#{v}'" }.to_sentence} in #{self}. There can only be a template file or inline render method per variant."
end
errors
end
end
def variants_from_inline_calls(calls)
calls.reject { |call| call == :call }.map do |variant_call|
variant_call.to_s.sub("call_", "").to_sym
end
end
end
ActiveSupport.run_load_hooks(:view_component, self)
end
end