A framework for building reusable, testable & encapsulated view components in Ruby on Rails
open sourceMITself-hostablefree
ViewComponent turns pieces of Rails views into components: a Ruby class that declares what it needs in its initializer, paired with a template. Because a component is a plain object, it can be unit tested on its own with render_inline and Capybara matchers (GitHub says over 100 times faster than similar controller tests), and its benchmark shows rendering about 2.5 times faster than partials. Slots, previews and testing helpers are documented on viewcomponent.org. Version 4 is in long-term support and described as feature-complete.
Problems it solves
- our Rails partials take a dozen locals and nobody knows which ones are required
- unit test a piece of a Rails view without a full controller test
- build a design system of reusable UI components for a server-rendered Rails app
- partials are slow to render on our busiest page
- preview every state of a UI component in isolation
- move view logic out of helpers into something testable
- components with named slots for header, body and footer in Rails
- encapsulate a button or card so it looks the same on every page
Features
- Ruby class plus template per component
- unit tests with render_inline
- Capybara matchers in tests
- slots
- previews
- about 2.5x faster than partials in its benchmark
- long-term support release (4.x)
Alternatives
The same job
These do what ViewComponent does.
- Phlex Object-oriented views in Ruby