Last active
April 10, 2023 15:01
-
-
Save bradgessler/cd91d5f2e333b99eed2fc0c3f76d827b to your computer and use it in GitHub Desktop.
Sane way to call a ViewComponent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copy this file to ./app/views/component_helper.rb if you want to unlock ViewComponent rendering super powers. | |
module ComponentHelper | |
# Instead of the awkward `render FooComponent.new(title: "foo")` calls in Rails templates, | |
# use a method like `foo_component title: "foo"`. | |
def method_missing(method_name, *args, **kwargs, &block) | |
if method_name.end_with? "_component" | |
component_class = method_name.to_s.classify.constantize | |
component = component_class.new(*args, **kwargs) | |
component.render_in(self, &block) | |
else | |
super(*args, *kwargs, &block) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment