talira

Object-oriented views in Ruby

open sourceMITself-hostablefree

Phlex is an MIT-licensed Ruby gem for building HTML, SVG and CSV views as plain Ruby classes: a component builds its markup with Ruby methods, keyword arguments and blocks instead of an ERB template, which makes unclosed tags hard to write and is designed to structurally prevent cross-site scripting. Because views are Ruby, tools like RuboCop, Ruby LSP and SimpleCov work on them, and the docs cover kits, caching, fragments, streaming and testing. phlex-rails integrates it with Rails: it supports Rails helpers and works alongside ERB, ViewComponent, Stimulus, Turbo and Tailwind CSS. It was made by Joel Drapper and Will Cosgrove.

Problems it solves

  • our Rails partials have grown into a mess of locals and conditionals that nobody can test
  • write Rails views as Ruby classes instead of ERB templates so I can refactor them like normal code
  • build a component library for a server-rendered Rails app without adopting a JavaScript framework
  • lint, type-check and measure test coverage of my HTML views with the same Ruby tools as the rest of the app
  • ERB makes it too easy to forget to escape user input in our Rails views
  • rendering many small extracted view components in Rails gets slow
  • generate SVG icons and CSV exports from the same Ruby view layer as my HTML
  • a lighter alternative to Rails' ActionView for a Ruby web app that isn't Rails
  • share UI components between several Ruby web apps as plain gems
  • cache and stream fragments of server-rendered pages from Ruby view components

Features

  • HTML, SVG and CSV views written as Ruby classes
  • structural templating that is designed to prevent cross-site scripting
  • kits, caching, fragments, streaming, snippets and testing for components
  • phlex-rails: Rails helpers, views and layouts, adoption guide for existing apps
  • works alongside ERB, ViewComponent, Stimulus, Turbo and Tailwind CSS
  • renders about 1.4 Gbps of HTML per core on an M3 Max MacBook Pro, by the project's own figure
  • follows BreakVer, with security patches for recent minor versions

Limitations

  • Doesn't run on Ruby older than 3.2: phlex 2.x requires Ruby 3.2 or newer1
  • Doesn't support Rails before 7.1: phlex-rails 2.x requires railties 7.1 or newer (and below 9)2

Alternatives

The same job

These do what Phlex does.

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

Compare Phlex with the top 3