crystal icon indicating copy to clipboard operation
crystal copied to clipboard

Provide alternative letter casings for `Enum`s

Open jgaskins opened this issue 1 year ago • 1 comments

Feature Request

Is your feature request related to a problem? Please describe clearly and concisely what is it.

Enums 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 enums 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 enums 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.

jgaskins avatar Jan 13 '24 04:01 jgaskins

My Lisp background means I subconsciously default to lisp-case/kebab-case for config files and other string values that I expect to parse. Having this for Enums (and maybe for YAML/JSON serialization? I can make another issue if that's of interest) would keep me from reinventing the wheel multiple times.

Is there some place in the stdlib that handles all the places where parsing a string like this might be useful? Seems like it would be used in multiple places.

MistressRemilia avatar Jan 13 '24 05:01 MistressRemilia