Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Last active April 10, 2023 15:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradgessler/cd91d5f2e333b99eed2fc0c3f76d827b to your computer and use it in GitHub Desktop.
Save bradgessler/cd91d5f2e333b99eed2fc0c3f76d827b to your computer and use it in GitHub Desktop.
Sane way to call a ViewComponent
# 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