Skip to content

Instantly share code, notes, and snippets.

@monochromer
Last active April 24, 2023 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monochromer/9ea8d3f4da1d8a056a55caac8c27b2e5 to your computer and use it in GitHub Desktop.
Save monochromer/9ea8d3f4da1d8a056a55caac8c27b2e5 to your computer and use it in GitHub Desktop.
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