-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
String-based Enums types #2978
Comments
I would suggest using a formatter for converting the string to symbols. |
I'd like to be able use types to mitigate errors so I can catch typos easily. For example:
The other option is to write my own struct that I can subclass and do that, but |
require "json"
enum EventType
PENDING = 1
IN_PROGRESS = 2
COMPLETE = 3
def to_json(io)
io << '"'
to_s(io)
io << '"'
end
end
struct MyEvent
JSON.mapping({
name: String,
event_type: EventType,
})
end
p event = MyEvent.from_json("{ \"name\": \"blabla\", \"event_type\": \"PENDING\" }")
# => MyEvent(@name="blabla", @event_type=PENDING)
puts event.to_json
# => {"name":"blabla","event_type":"PENDING"} |
enum is BTW, if we can provide the convert rules in Edited: like struct MyEvent
JSON.mapping({
name: String,
event_type: {PENDING: :foo, IN_PROGRESS: :bar}
})
end
p event = MyEvent.from_json("{ \"name\": \"blabla\", \"event_type\": \"PENDING\" }")
# => MyEvent(@name="blabla", @event_type=:foo)
puts event.to_json
# => {"name":"blabla","event_type":"PENDING"} |
I believe that this issue should be closed as "status:wantfix". |
The example from @ysbaddaden shows, that the intended result can already be achieved in a different way. BTW |
Let's close this. Enums need an integer value. For a string representation the solutions above are good enough. |
I'd like to have the ability to have
String
basedEnum
s. My current use case is I'm usingJSON.mapping
to turn JSON output into typed classes, but I'd like the ability to do something like this:I'm not sure how a
event_type
value that doesn't match should work, maybe some sort of catch allEventType::Other
like how there'sAll
andNone
for the integer ones?Thoughts?
The text was updated successfully, but these errors were encountered: