Documentation

View Helpers

Rails Designer includes various view helpers to clean up your code. Rails helpers are modules that offer methods for generating HTML and other utility functions, ideal for removing repetitive global code in your app.

Set up

You can enable each individual helper method. In config/initializers/rails_designer.rb, look for config.view_helpers.

# …
config.view_helpers = ["component", "stream_notification", "string_to_color", "label_for"]
# …

You can remove any to disable the helper in your app.

Available helpers

These are the current available helpers in Rails Designer:

Component

Rendering a ViewComponent is pretty verbose out-of-the-box:

render(AvatarComponent.new(user: Current.user))

Instead you can use the component-helper like this:

component "avatar", user: Current.user

Label For

Rails Designer’s FormLabelComponent can be more easily written with this helper. Instead of:

render(FormLabelComponent.new(form: form, field: "email"))

You can write it like this:

label_for form: form, field: "email"

Stream Notification

Displaying flash messages (notifications) is quite common, even more so with Rails Designer’s Notifications. It’s quite annoying to write the same lines of code every time you want to display a notification through a Turbo Stream:

# app/views/users/create.turbo_stream.erb
<%= turbo_stream.append "notification" do %>
  <⁠%= render NotificationComponent.new(message: "User Saved") %>
<% end %>

Use stream_notification instead:

# app/views/users/create.turbo_stream.erb
<%= stream_notification "User Saved" %>

The first attribute is the message to be displayed. Other options are:

  • type (notice, success, alert, warning);
  • stacked (true or false);
  • description;
  • time_delay (in seconds);
  • progress_indicator (either spinner or progress_bar);
  • primary_link;
  • secondary_link

With all options it might look like this:

# app/views/users/create.turbo_stream.erb
<%= stream_notification "Suspicious Login Attempt",
    type: "alert",
    description: "We've prevented a login from an unrecognized source.",
    time_delay: 30,
    progress_indicator: "progress_bar",
    primary_link: {
      label: "Review Activity",
      path: "#"
    },
    secondary_link: {
      label: "It's me",
      path: "#"
    }
%>

String To Color

Convert any string to a matching Tailwind CSS color. Useful to add a consistent color to any user’s name.

string_to_color("robin")

It defaults to the Tailwind CSS colors, but you can pass any array with colors:

string_to_color("robin", colors: ["#FF6B6B", "#4ECDC4", "#1A535C", "#FFD700", "#FF6347", "#20B2AA", "#778899", "#7B68EE", "#DB7093", "#8FBC8F"])

Helper generator

If you want to make tweaks to any of these helpers, run the following generator:

bin/rails generate rails_designer:helper helper_name

This will copy the helper into your app/helpers folder.

You can also run bin/rails generate rails_designer:helper --help to view help.