DEV Community

Rails Designer
Rails Designer

Posted on Originally published at railsdesigner.com on

A form builder to style every Rails form

Every Rails app I have started the last few years, includes the same custom form builder. I have copied this one file from app to app, it is not pretty but it keeps every input style in one place and it turns four lines of markup into one (think of it as simpler simple_form—if you know, you know—except you own the code, which I like in this case).

image.png

Add is as the default

First, look at what the form looks like when I write it. Here is a part of the settings page in the demo app.

<%= form_with model: @workspace do |form| %>
  <%= form.input :name %>
  <%= form.input :website, label_suffix: "Optional" %>
  <%= form.input :description, as: :text %>

  <%= form.submit %>
<% end %>

Enter fullscreen mode Exit fullscreen mode

No need to add classes or wrapper divs. The builder adds it.

To make form_with use it everywhere, set the default once.

class ApplicationController < ActionController::Base
+ default_form_builder FormBuilder
end

Enter fullscreen mode Exit fullscreen mode

Put FormBuilder in lib/ (it is where I put all files that are reusable verbatim in any Rails app).

Every field is styled in one place

The builder redefines the native field helpers in a loop. Each one gets the same class string before it renders.

%w[
  text_field
  email_field
  password_field
  search_field
  telephone_field
  url_field
  # …
].each do |field_type|
  define_method(field_type) do |method, options = {}|
    options[:class] = options[:class].presence || class_names(input_css, options[:additional_class])
    options.delete(:additional_class)

    super(method, options)
  end
end

Enter fullscreen mode Exit fullscreen mode

options[:class].presence || … adds only the default class, when no class is passed. If I need something else, I can easily override it.

additional_class is for one-off classes on top of the default class and then removes itself, so it never is added to the HTML.

The CSS is defined in input_css (Tailwind CSS class, but you can just use normal CSS).

def input_css
  <<~CSS
    w-full px-2.5 py-1.5
    text-sm font-normal text-gray-900
    bg-white
    border-0 ring ring-gray-200/80 rounded-sm
    hover:ring-gray-300
    focus:ring focus:ring-brand-300
    outline-none appearance-none
  CSS
end

Enter fullscreen mode Exit fullscreen mode

This is in way a design system. Every input, text area, select and file field uses it. I change the radius in one place and every form in the app changes. Swap Tailwind for plain CSS in seconds (who does not want that!).

The input method ❤️

The native helpers render an input and nothing else. input renders a whole field: label, input, hint and a wrapper (div) to wrap them (orly! 🦉).

def input(attribute, options = {})
  label_suffix = options.delete(:label_suffix)
  hint = options.delete(:hint) || I18n.t("hints.#{attribute}", default: nil)

  @template.content_tag(:div, data: {slot: "field"}, class: options[:field_css] || field_css) do
    @template.safe_join([
      label(attribute, options),
      input_field(attribute, options),
      (@template.content_tag(:p, hint.html_safe, class: "mt-0.5 px-0.5 text-xs font-light text-gray-500") if hint)
    ].compact)
  end
end

Enter fullscreen mode Exit fullscreen mode

(yes, it is a bit—understatement—hard to follow. but it works!)

The native (naive?) way is four lines of markup per field.

<div class="w-full">
  <%= form.label :name %>

  <%= form.text_field :name, class: "w-full px-2.5 py-1.5 text-sm …" %>
</div>

Enter fullscreen mode Exit fullscreen mode

With my builder it is one line:

<%= form.input :name %>

Enter fullscreen mode Exit fullscreen mode

label_suffix puts a quiet “Optional” at the far right. hint prints a helper line under the field. Both are read from the locale file, so the same field always looks the same.

en:
  labels:
    slug: "Workspace URL"
  hints:
    slug: "Lowercase letters, numbers and hyphens only."

Enter fullscreen mode Exit fullscreen mode

form.input :slug now shows “Workspace URL” and its hint with no extra options. Rename the label once and every form updates.

The wrapper also spaces itself (the field_css uses a Tailwind arbitrary variant).

[AD] Spinal CMS: Git-based CMS for static site generators

def field_css = "w-full [&[data-slot='field']+[data-slot='field']]:mt-4"

Enter fullscreen mode Exit fullscreen mode

Any field right after another field gets a top margin without space-y on the parent or manual margins.

Automatic field type

input calls input_field, which picks the right helper for the attribute.

def input_field(attribute, options)
  return select(attribute, options[:collection], {}, options.except(:as, :label, :collection)) if options[:collection]

  send(FIELD_TYPES.fetch(options[:as] || type_for(attribute), :text_field), attribute, options.except(:as, :label, :collection))
end

Enter fullscreen mode Exit fullscreen mode

type_for guesses from the attribute name first, then checks the object.

def type_for(attribute)
  return :email if attribute.to_s.end_with?("email")
  return :password if attribute.to_s.include?("password")
  return :url if attribute.match?(/url|website|site/)
  return :string unless valid?(attribute)

  @object.type_for_attribute(attribute.to_s).type
rescue NoMethodError
  :string
end

Enter fullscreen mode Exit fullscreen mode

An attribute ending in email becomes an email_field. One containing password becomes a password_field. If the name gives nothing away, type_for_attribute reads the model type. A datetime becomes datetime_local_field. A decimal becomes number_field.

I only add as: when the name and type both are incorrect. I update the form builder whenever I need too.

Labels, hints and errors

The builder overrides label too. It checks the object for errors on that attribute and changes color when it finds any.

def label(attribute, text = nil, options = {}, &block)
  field_errors = @object.respond_to?(:errors) ? @object.errors.where(attribute) : nil

  label_options[:class] = token_list(
    "flex items-center gap-1 text-sm font-normal",
    {"text-gray-600": field_errors&.none?, "text-red-600": field_errors&.any?}
  )

  super(attribute, label_options) do
    safe_join([
      (icon("circle-alert", class: "size-3.5") if field_errors&.any?),
      label_text
    ].compact)
  end
end

Enter fullscreen mode Exit fullscreen mode

The demo adds a few errors to show the states.

@workspace.errors.add(:slug, "is already taken")
@workspace.errors.add(:terms, "must be accepted")

Enter fullscreen mode Exit fullscreen mode

The label turns red and adds a small alert icon (with a small transition). The icons uses Rails Icons (obviously). Remove the include and the icon line if you do not use Rails Icons (sad! 🙅‍♀️).

Selects, checkboxes and radios

Selects are the fussiest native helper. The builder styles them and draws its own chevron, so I never add a wrapper.

html_options[:class] = class_names(
  input_css,
  "bg-[length:16px] bg-[right_6px_center] bg-no-repeat pr-8",
  "bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg…%3E')]"
)

Enter fullscreen mode Exit fullscreen mode

appearance-none in input_css removes the browser arrow. The builder shows a chevron from a data URI instead. It works the same on select, collection_select and grouped_collection_select.

For toggles, check_box and radio_button render the input and its label together inside a shared wrapper.

def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
  label_text = block_given? ? @template.capture { yield } : options.delete(:label) || method.to_s.humanize

  toggle_wrapper do
    super(method, options, checked_value, unchecked_value) + label(method, label_text)
  end
end

Enter fullscreen mode Exit fullscreen mode

The label is next to the box and dims when the input is disabled, all via peer utilities. When I need the plain helper, I add plain: true and get Rails’ version back.

The file also has a few aliases. phone_field, textarea, checkbox, and collection_checkboxes are there because I always forget Rails’ singular and plural names (I am kind to myself now!).


Further thoughts

This builder is a simpler simple_form. It is not tidy—it is rather horrendous as it has grown over a few years, and some methods are messier than I would write today. That is fine, it works and I might refactor at some point.

The builder is my form design system. A few things I keep meaning to add. Move the class strings into a config object so a theme can replace them. Let field_css come in per form, not per field. Add a preview for Active Storage uploads. This is not an open invite (hint, hint, wink, wink).

As always, the code can be found on GitHub. Copy the file, set default_form_builder and have fun with it.

Top comments (0)