-
Notifications
You must be signed in to change notification settings - Fork 21.9k
Introduce class_names helper #37918
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Introduce class_names helper #37918
Conversation
As a follow-up to #37872, this change introduces a class_names view helper to make it easier to conditionally apply class names in views. Before: <div class="<%= item.for_sale? ? 'active' : '' %>"> After: <div class="<%= class_names(active: item.for_sale?) %>"> We've been using this helper in the GitHub monolith since 2016. Co-authored-by: Aaron Patterson <tenderlove@github.com>
Thanks for this handy helper. We should add a changelog entry to this method. |
Add changelog entry for #37918
# class_names({ foo: true, bar: false }) | ||
# # => "foo" | ||
# class_names(nil, false, 123, "", "foo", { bar: true }) | ||
# # => "foo bar" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@joelhawksley The output mentioned in the docs in wrong. I tried it in one of the application and integer are added to the output string.
123.present?
will not return false
here(https://github.com/rails/rails/pull/37918/files#diff-3d863df5229eeafadb6df53160605a5bR348)
123 foo bar
Taking the ideas introduced in rails#37872 and rails#37918, eliminating the use of a switch-on-class, and generalising the production of tags to any context. Passes an accumulator/result array to minimise allocations.
This improvement follows on from a recent PR on the components lib[0] where Rails' class_names[1][2] was used to improve the building of lists of HTML classes. Unfortunately it returns a space-separated string instead of an array - and the method it uses to actually build up the classes, `#build_tag_values`, is private, which makes utilsing it a bit of a pain. Instead here we're implementing a minimal version of it called `#build_classes`. It uses more-or-less the same class-building strategy as `#build_tag_values` but is less flexible in terms of args it accepts. [0] x-govuk/govuk-components/pull/264 [1] rails/rails#37918 [2] https://www.bigbinary.com/blog/rails-6-1-introduces-class_names-helper
As a follow-up to #37872,
this change introduces a class_names view helper
to make it easier to conditionally apply class names
in views.
Before:
<div class="<%= item.for_sale? ? 'active' : '' %>">
After:
<div class="<%= class_names(active: item.for_sale?) %>">
We've been using this helper in the GitHub monolith
since 2016.
Co-authored-by: Aaron Patterson tenderlove@github.com