gjaldon / ecto_enum

Ecto extension to support enums in models
MIT License
562 stars 131 forks source link

Using Enums as constants #87

Closed zph closed 5 years ago

zph commented 5 years ago

Hello :)

I've been using EctoEnum and want some additional functionality from it.

I was pleased to see about the auto type generation! Next I'd like to be able to use the enums around the codebase as constants representing the different enum values (pseudo code to demonstrate how it works in typescript)

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

# Elsewhere it's used as
Direction.Up

In elixir and with Ecto enum, I think this would become macro'd function definitions for each member of the enum, that return either the original string or symbol, or if an integer value is assigned in the keyword list, then it would return that.

This solves a problem where these enums are re-implemented in many non-database related modules.

defenum StatusEnum, registered: 0, active: 1, inactive: 2, archived: 3

# Then elsewhere I want to use 
> StatusEnum.registered()
0

In the case of string or symbol backed enums, it would return the value itself

defenum StatusEnum, registered: "registered", active: "active", inactive: "active", archived: "archived"
# short-cut way of using string-backed enums
defenum StatusEnum, ["registered", "active", "inactive", "archived"]

# In both cases this would allow
> StatusEnum.registered()
=> "registered"

Is this a PR you're interested in accepting if I put one together? Do you see a better alternate that solves this problem?

gjaldon commented 5 years ago

@zph I think this idea is sound and would definitely welcome a PR. :)

zph commented 5 years ago

Closing issue since this is now a PR #90