class ActionComponent::Component
Represents a component with a template, style and javascript file
Renders a given component
Renders a given component
Attributes
component_path[R]
view_model_data[R]
Public Class Methods
helper_object()
click to toggle source
# File lib/actioncomponent/component.rb, line 6 def helper_object @helper_object = Class.new(ActionView::Base) do include ::Rails.application.routes.url_helpers include ::Rails.application.routes.mounted_helpers end.new end
helper_vm_params()
click to toggle source
# File lib/actioncomponent/component.rb, line 13 def helper_vm_params { h: helper_object, helper: helper_object } end
new(component_path:, lookup_context: nil, view_model_data: {})
click to toggle source
# File lib/actioncomponent/component.rb, line 23 def initialize(component_path:, lookup_context: nil, view_model_data: {}) @component_path = component_path.to_s.gsub(%r{^/}, '') @lookup_context = lookup_context @view_model_data = view_model_data end
Public Instance Methods
create_view_model()
click to toggle source
# File lib/actioncomponent/component.rb, line 45 def create_view_model vm_class = ActionComponent::Component::ViewModel begin vm_class = find_custom_vm_class! rescue NameError vm_class = ActionComponent::Component::ViewModel end vm_class.new(**view_model_data.merge(view_model_default_data)) end
full_component_path()
click to toggle source
# File lib/actioncomponent/component.rb, line 63 def full_component_path Rails.root.join(ActionComponent.configuration.components_path) end
lookup_context()
click to toggle source
# File lib/actioncomponent/component.rb, line 37 def lookup_context @lookup_context ||= ActionView::LookupContext.new( [ full_component_path ] ) end
render()
click to toggle source
# File lib/actioncomponent/component.rb, line 29 def render renderer.render(component_path: @component_path) end
renderer()
click to toggle source
# File lib/actioncomponent/component.rb, line 33 def renderer ActionComponent::Component::Renderer.new(lookup_context, create_view_model) end
view_model_default_data()
click to toggle source
# File lib/actioncomponent/component.rb, line 57 def view_model_default_data # lookup_context is necessary for when there is an exception in our template # this is used in order to better describe the error stack self.class.helper_vm_params.merge(lookup_context: lookup_context) end
Private Instance Methods
find_custom_vm_class!()
click to toggle source
# File lib/actioncomponent/component.rb, line 69 def find_custom_vm_class! vm_file_path = Pathname.new(component_path).join(ActionComponent.configuration.view_model_file_name) vm_class = ActiveSupport::Inflector.camelize(vm_file_path).constantize unless vm_class.ancestors.include?(ActionComponent::Component::ViewModel) error_msg = "#{vm_class} cannot be used as a ViewModel. Make sure that it inherits from ActionComponent::Component::ViewModel." raise ActionComponent::Component::InvalidVMError, error_msg end vm_class end