Link Search Menu Expand Document

ViewComponent

A framework for building reusable, testable & encapsulated view components in Ruby on Rails.

What is a ViewComponent?

ViewComponents are Ruby objects used to build markup. Think of them as an evolution of the presenter pattern, inspired by React.

When should I use ViewComponents?

ViewComponents best for templates that are reused or benefit from being tested directly. Heavily reused partials and templates with significant amounts of embedded Ruby often make good ViewComponents.

Benefits

Testing

Unlike traditional Rails templates, ViewComponents can be unit tested. In the GitHub codebase, ViewComponent unit tests are over 100x faster than similar controller tests.

With ViewComponent, integration tests can be reserved for end-to-end assertions, with permutations covered at the unit level.

Data Flow

Traditional Rails templates have an implicit interface, making it hard to reason about their dependencies. This can lead to subtle bugs when rendering the same template in different contexts.

ViewComponents use a standard Ruby initializer that clearly defines what is needed to render, making reuse easier (and safer) than with partials.

Performance

Based on our benchmarks, ViewComponents are ~10x faster than partials.

Code quality

Template code often fails basic Ruby standards: long methods, deep conditional nesting, and mystery guests abound.

ViewComponents are Ruby objects, making it easy to follow (and enforce) code quality standards.

Design philosophy

ViewComponent is designed to integrate with Rails as seamlessly as possible, with the least surprise.

Contributors

ViewComponent is built by over a hundred members of the community, including:

asgerb bbugh bigbigdoudou blakewilliams bobmaerten bradparker cesariouy cover czj dark-panda davekaro dukex dylnclrk elia franco franks921 fsateler fugufish g13ydson horacio jaredcwhite jcoyne jensljungblad joelhawksley johannesengl jonspalmer juanmanuelramallo jules2689 kaspermeyer kylefox manuelpuyol mattbrictson maxbeizer mellowfish metade michaelem mixergtz mrrooijen nashby nshki nshki rainerborene rdavid1099 rmacklin seanpdoyle simonrand skryukov smashwilson spdawson Spone swanson tbroad-ramsey tclem tenderlove tonkpils traels vinistock xronos-i-am matheusrich


Getting started →