Skip to content

Instantly share code, notes, and snippets.

@andrewkatz
Created May 13, 2021 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewkatz/f6d9cb545c20a6238be92b82a611012e to your computer and use it in GitHub Desktop.
Save andrewkatz/f6d9cb545c20a6238be92b82a611012e to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# Easier access to components in templates. So instead of doing:
#
# <%= render SectionComponent.new(title: 'Foo') do |c| %>
# <p>My content</p>
#
# <% c.subsection do %>
# <p>Cool</p>
# <% end %>
# <% end %>
#
# You can do:
#
# <%= section title: 'Foo' do |c| %>
# <p>My content</p>
#
# <% c.subsection do %>
# <p>Cool</p>
# <% end %>
# <% end %>
module ComponentHelper
Dir.glob(Rails.root.join('app', 'components', '*.rb')).each do |component_file|
component = component_file.match(%r{/([\w_]+)_component.rb})[1]
define_method component do |**options, &block|
klass = "#{component.classify}Component".constantize
render klass.new(**options), &block
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment