232 Partials and ViewComponent [1.5d]

Posted . Visible to the public.

Views grow. The same card, button or navigation shows up on ten screens, and soon the same twelve lines of HTML live in ten places. Rails partials are the first tool against this; ViewComponent is the second, for components that carry logic, helpers, CSS and JavaScript of their own. This card teaches you to give your views a small, readable vocabulary of components.

Important

Work on this lesson in advisor mode.

Learning goals

  • You can explain how a partial exposes an API to its callers: through locals, and by accepting a block that the partial yields.
  • You can explain the benefits of a view component over a partial: it hides HTML details behind an explicit interface and co-locates the template with its helpers, its JavaScript and its CSS.
  • You can decide when a piece of view code deserves extraction at all, and whether a partial, a helper or a component is the right form.
  • You can extract recurring HTML into partials and helpers so that views read as a terse description of the screen.
  • You can build a ViewComponent following our conventions, and write a unit test for it.

Resources

Read what's new to you, skim what's familiar, skip what you already master. Stop when you can meet the learning goals.

Your agent can also generate an overview, a tutorial or an explanation for anything here, tailored to what you already know. Just ask.

Partials

ViewComponent

Exercises

1. Find the components in MovieDB

Go through your MovieDB views and identify the recurring pieces: cards, sections, buttons, the navigation, tabs, form rows. Extract them into partials and helpers.

The goal is that every view gets a nice, terse API to use a component without duplicating its HTML anywhere. Judge the result by reading the views afterwards: they need to look nice.

2. Turn partials into components

Convert some of your partials into ViewComponent components. Your MovieDB comes with view_component preconfigured and an example component, Alert in app/components — follow its style and conventions.

Aim for the same thing as before — a nice API for the views. Then turn one of your JavaScript components from Unobtrusive JavaScript components (e.g. the spoiler or the searchable list) into a view component, and co-locate its JavaScript and its BEM block's styles with it, like alert.rb, alert.js and alert.sass. application.js picks up every .js and .sass file in app/components. Write a component spec for at least one of your components.

Profile picture of Henning Koch
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra Curriculum (2026-08-31 15:28)