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

Auto define enum variants as functions #90

Open
wants to merge 6 commits into
base: master
Choose a base branch
from

Conversation

zph
Copy link

@zph zph commented Aug 29, 2019

Implements #87

This patch allows using enum variants as you would use a constant in some languages or a full featured Enum in others.

When variants are defined on an enum, a matching function will be defined for reducing code re-definitions.

It allows for usage as:

defenum StatusEnum, ["registered", "active", "inactive", "archived"]

> StatusEnum.registered()
=> "registered"

Complex atom types are also coerced into idiomatic names:

defenum StatusEnum, [:"on-hold"]

> StatusEnum.on_hold()
=> :"on-hold"

This PR works for both arity 2 and 3 versions of defenum. I had tested it for different cases in PG but have not deeply assessed any changes needed for MySQL.

You're welcome to tweak the PR for small changes and I'm happy to adjust it myself if something more thorough is needed.

:D

ie

```
defenum(Color, :color, [:red, :green])
Color.red() => :red
```
…stants

This macro in the patch allows for using these enums inside the codebase
to represent the same value, instead of needing to redefine them :)

Thus:

```
defenum(Status, :status, [:good, :bad, :other])
Status.good() => :good
```
Previously dashes in the atom would break the function definition and
make it non-standard Elixir (ie we need valid atoms for function names).
@zph
Copy link
Author

zph commented Aug 29, 2019

Note: this works for some cases but not inside matches and in function heads. To make these work cleanly it needs to be a defmacro and be inlined during compilation.

We can hold off on merging this until I can implement that component.

The conversion to Macros broke tests, revising :) and will comment when ready for review.

@zph zph mentioned this pull request Aug 30, 2019
@zph
Copy link
Author

zph commented Sep 12, 2019

This is ready for review and I'm using it currently as it is in my own projects :).

@axelson
Copy link

axelson commented Nov 2, 2019

This would be really helpful to ensure that we're using the right values as constants in the rest of the code-base (i.e. when creating records). Can this be merged? Although it could use some docs.

@rebebop
Copy link

rebebop commented May 17, 2020

Are there any plans to merge this 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.

None yet

4 participants