Skip to main content

How to use enum enumerize on rails

We are using enumerize gem to define our enums. Here are few things to keep in mind when using it.

https://github.com/brainspec/enumerize

class ProSubscription < ActiveRecord::Base
extend Enumerize

enumerize :level, in: %w(premium pro enterprise global global_plus), predicates: true, scope: true
enumerize :subscription_type, in: %w(monthly yearly biennially lifetime), predicates: true, scope: true
end

When defining enums this way, you now have access to bunch of helper methods:-

Example:-​

irb(main):003:0> ap ProSubscription.level.values
[
[0] "premium",
[1] "pro",
[2] "enterprise",
[3] "global",
[4] "global_plus"
]
=> nil
irb(main):004:0> ap ProSubscription.subscription_type.values
[
[0] "monthly",
[1] "yearly",
[2] "biennially",
[3] "lifetime"
]
=> nil
irb(main):005:0> p = ProSubscription.first
=> #<ProSubscription id: 10, credit_card_id: 10, price: 499, level: "premium", subscription_type: "monthly", user_id: 13 ...

irb(main):006:0> p.subscription_type.monthly?
=> true
irb(main):007:0> p.subscription_type.yearly?
=> false
irb(main):008:0> p.level.premium?
=> true
irb(main):009:0> p.level.pro?
=> false
irb(main):010:0>


Predicates​

Predicates helps you define a helper method with question mark, example pro_subscription.yearly?

Scopes​

Scopes helps you define bunch of scopes per enum values, for example, if you like to query all pro_subscription with yearly subscription type you can do something like

ProSubscription.with_subscription_type(:yearly)