DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.04k stars 85 forks source link

Create class enum accessor #135

Closed jas14 closed 1 year ago

jas14 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

Should be all set!

DmitryTsepelev commented 1 year ago

LGTM, thank you 🙂