Skip to content
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

Feat: Enum::StringConverter(T) #9887

Closed

Conversation

caspiano
Copy link
Contributor

@caspiano caspiano commented Nov 6, 2020

Adds Enum::StringConverter(T), a converter to be used with JSON::Serializable to write and read
an Enum exclusively as a String.

This is useful if you wish to serialise to String, instead of
the default of a number representation of the Enum.

Closes #9881

Includes fixes to minor typos in a few serialization examples.

Usage:

require "json"
                                                                            
class EnumStringMessage
  include JSON::Serializable
                                                                            
  enum Hint
    Up
    Down
  end
                                                                            
  @[JSON::Field(converter: Enum::StringConverter(EnumStringMessage::Hint))]
  getter hint : Hint
end
                                                                            
message = EnumStringMessage.from_json(%({"hint":"Up"}))
message.hint    # => EnumStringMessage::Hint::Up
message.to_json # => %({"hint":"Up"})

@caspiano caspiano force-pushed the feat/enum-string-converter branch from 4a33be8 to 4a76b58 Compare November 6, 2020 01:31
@caspiano caspiano force-pushed the feat/enum-string-converter branch from 4a76b58 to 5b3f7d3 Compare November 6, 2020 01:48
@caspiano caspiano marked this pull request as draft November 6, 2020 01:57
@Sija
Copy link
Contributor

Sija commented Nov 6, 2020

My 2c:

  • I'd make it a default
  • I'd use to_s.underscore for serializing

@caspiano
Copy link
Contributor Author

caspiano commented Nov 7, 2020

@Sija Yeah, I agree, I'd much prefer to_s.underscore.

I'll whip up another PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[RFC] Enum JSON string converter
2 participants