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

Create class enum accessor #135

Merged
merged 3 commits into from
Feb 19, 2023

Conversation

jas14
Copy link
Contributor

@jas14 jas14 commented Dec 14, 2022

Intro 👋

Hi there! I hope it was all right to open this PR directly. I'm a first-time contributor so go easy on me and let me know how you'd like me to contribute this, if it's welcome.

This PR

Take a class with an enum defined:

class Configuration
  include StoreModel::Model

  enum :status, {off: 0, on: 1}
end

Currently, it's only possible to access the enum mapping on instances:

Configuration.new.status_values # => {:off=>0, :on=>1}

But the mapping is defined on the class, so there's no reason this shouldn't also work, which is how it also works in ActiveRecord:

Configuration.status_values # => {:off=>0, :on=>1}

This PR defines that method on the class.

Bonus

In Rails, it's also possible to access the enum mapping via the pluralized enum name, e.g.

Configuration.statuses

instead of

Configuration.status_values

To support both the Rails style pluralized name style as well as the current StoreModel style, I also added aliases with the Rails-style names to the StoreModel-style names.

@DmitryTsepelev
Copy link
Owner

Hey hey! LGTM!

There is a Rubocop failure, please take a look at it and we'll be good to go 🙂Please ignore JRuby failure, it happens on master as well

@jas14
Copy link
Contributor Author

jas14 commented Dec 15, 2022

Should be all set!

@DmitryTsepelev
Copy link
Owner

LGTM, thank you 🙂

@DmitryTsepelev DmitryTsepelev merged commit 5dbe52c into DmitryTsepelev:master Feb 19, 2023
@jas14 jas14 deleted the class-enum-accessor branch February 28, 2023 15:14
define_method("#{name}_values") { mapping }
alias_method(ActiveSupport::Inflector.pluralize(name), "#{name}_values")
singleton_class.define_method("#{name}_values") { mapping }
singleton_class.alias_method(ActiveSupport::Inflector.pluralize(name), "#{name}_values")
Copy link

@BoberMod BoberMod Mar 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's breaking change.
What if enum is already in plural form?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@BoberMod good point, I'll open a PR shortly to fix this.

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.

3 participants