class ViewComponent::Base
def inherited(child)
- Private: -
def inherited(child) # Compile so child will inherit compiled `call_*` template methods that # `compile` defines compile # Give the child its own personal #render_template_for to protect against the case when # eager loading is disabled and the parent component is rendered before the child. In # such a scenario, the parent will override ViewComponent::Base#render_template_for, # meaning it will not be called for any children and thus not compile their templates. if !child.instance_methods(false).include?(:render_template_for) && !child.compiled? child.class_eval <<~RUBY, __FILE__, __LINE__ + 1 def render_template_for(variant = nil, format = nil) # Force compilation here so the compiler always redefines render_template_for. # This is mostly a safeguard to prevent infinite recursion. self.class.compile(raise_errors: true, force: true) # .compile replaces this method; call the new one render_template_for(variant, format) end RUBY end # If Rails application is loaded, add application url_helpers to the component context # we need to check this to use this gem as a dependency if defined?(Rails) && Rails.application && !(child < Rails.application.routes.url_helpers) child.include 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. # We use `base_label` method here instead of `label` to avoid cases where the method # owner is included in a prefix like `ApplicationComponent.inherited`. child.identifier = caller_locations(1, 10).reject { |l| l.base_label == "inherited" }[0].path # If Rails application is loaded, removes the first part of the path and the extension. if defined?(Rails) && Rails.application child.virtual_path = child.identifier.gsub( /(.*#{Regexp.quote(ViewComponent::Base.config.view_component_path)})|(\.rb)/, "" ) end # Set collection parameter to the extended component child.with_collection_parameter provided_collection_parameter if instance_methods(false).include?(:render_template_for) vc_ancestor_calls = defined?(@__vc_ancestor_calls) ? @__vc_ancestor_calls.dup : [] vc_ancestor_calls.unshift(instance_method(:render_template_for)) child.instance_variable_set(:@__vc_ancestor_calls, vc_ancestor_calls) end super end