Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby on Rails view component helpers
# https://www.innoq.com/en/blog/rails-frontend-components/
# app/helpers
module ComponentHelper
def component(name, data: {}, &block)
render_component("#{name}/#{name}", { data: data }, &block)
end
private
def render_component(name, locals, &block)
if block_given?
# using `layout` is a trick to allow passing blocks to partials
# (cf. http://stackoverflow.com/a/2952056)
render layout: name, locals: locals, &block
else
render partial: name, locals: locals
end
end
end
=begin
# For this to work, we've extended `ApplicationController`
to include `append_view_path Rails.root.join("app", "components")`.
.
├── app
│ ├── components
│ │ ├── …
│ │ ├── image_gallery
│ │ │ ├── _image_gallery.html.haml
│ │ │ ├── _image_gallery.scss
│ │ │ ├── image_gallery.js
│ │ │ └── image_gallery.yml
│ │ └── …
=end
=begin
:ruby
# _image_gallery.html.haml
# parameters are passed into the component's template explicitly
images = data.fetch(:images) # required
selected_index = data.fetch(:selected_index, 0)
%image-gallery
%ul
- images.each_with_index do |image, index|
%li{ class: index == selected_index ? "is-active" : nil }
= image_tag image.src, alt: image.alt
=end
# = component :image_gallery, data: { images: @images }
# https://api.rubyonrails.org/v6.0/classes/ActionView/PartialRenderer.html
# https://goiabada.blog/rails-components-faedd412ce19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.