-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
Feature Request
Is your feature request related to a problem? Please describe clearly and concisely what is it.
Enum
s provide only a single string representation, based on the constant name as written. This is a good start, but sometimes insufficient. I've written a lot of different enum
types in my apps that required custom methods for serialization to/from DBs and third-party services as well as displaying on web pages.
It's understandable to have to write these, but I was copy/pasting the same methods over and over again between enum
types (because enum
s can't include mixins 😬) and even across apps.
I wasn't sure how many people ran into this, but I saw this thread on the forum today, so I'm clearly not the only one that needs alternative representations.
Describe the feature you would like, optionally illustrated by examples, and how it will solve the above problem.
The way I usually go about it is to define a method for each letter casing style I need. Usually that's:
-
snake_case
-
kebab-case
-
SCREAMING_SNAKE_CASE
-
one I call "Human friendly" which is essentially
to_s.underscore.tr("_", " ").capitalize
I usually define the enum
constants in TitleCase/CamelCase/PascalCase, so I don't normally need to provide a separate representation for it, but it might be a good idea to provide for enum
s that are in SCREAMING_SNAKE_CASE.
I posted #14226 earlier which illustrates a subset of this.
Describe considered alternative solutions, and the reasons why you have not proposed them as a solution here.
In the past, I've overridden to_s
for this, but then I had an issue where I needed multiple string representations of the same enum
. For example, a human-friendly one to display on a web page and a kebab-case one to send to a third-party service.
Does it break backward compatibility, if yes then what's the migration path?
Nope, and in fact Enum.parse
parses all of these representations (other than the human-friendly one) just fine.