Module: ViewComponentHelper
- Defined in:
- lib/view_component_helper/view_helper.rb,
lib/view_component_helper/railtie.rb,
lib/view_component_helper/version.rb
Overview
ViewComponentHelper Module
This module provides utility methods to assist with rendering ViewComponents within a Rails application. It aims to simplify the process of invoking and displaying components based on their file paths and additional arguments.
Defined Under Namespace
Classes: Railtie
Constant Summary collapse
- VERSION =
"0.9.1"
Class Method Summary collapse
- .define_render_method_for(component_class_name, method_name) ⇒ Object
- .load_components(component_loader = -> { Dir[Rails.root.join("app/components/**/*.rb")] }) ⇒ Object
- .valid_component_class?(component_class_name) ⇒ Boolean
Instance Method Summary collapse
- #render_view_component(path, *args, collection: nil, **kwargs, &block) ⇒ Object (also: #render_vc, #vc)
Class Method Details
.define_render_method_for(component_class_name, method_name) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/view_component_helper/view_helper.rb', line 41 def self.define_render_method_for(component_class_name, method_name) define_method(method_name) do |*args, collection: nil, **kwargs, &block| component_klass = component_class_name.constantize if collection render component_klass.with_collection(collection, *args, **kwargs, &block) else component_instance = component_klass.new(*args, **kwargs, &block) render component_instance end end end |
.load_components(component_loader = -> { Dir[Rails.root.join("app/components/**/*.rb")] }) ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/view_component_helper/view_helper.rb', line 27 def self.load_components(component_loader = -> { Dir[Rails.root.join("app/components/**/*.rb")] }) component_loader.call.each do |file| component_path = file[%r{components/(.*)\.rb$}, 1] component_class_name = component_path.camelize method_name = component_path.gsub("/", "_") define_render_method_for(component_class_name, method_name) if valid_component_class?(component_class_name) end end |
.valid_component_class?(component_class_name) ⇒ Boolean
37 38 39 |
# File 'lib/view_component_helper/view_helper.rb', line 37 def self.valid_component_class?(component_class_name) Object.const_defined?(component_class_name) && component_class_name.constantize < ViewComponent::Base end |
Instance Method Details
#render_view_component(path, *args, collection: nil, **kwargs, &block) ⇒ Object Also known as: render_vc, vc
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/view_component_helper/view_helper.rb', line 12 def render_view_component(path, *args, collection: nil, **kwargs, &block) component_klass = path.classify.constantize if collection render component_klass.with_collection(collection, *args, **kwargs, &block) else component_instance = component_klass.new(*args, **kwargs) component_instance.instance_exec(&block) if block_given? render(component_instance) end end |