简体   繁体   中英

Rails Enum: overriding getter to always compare with symbols instead of strings

Looking at ActiveRecord's Enum documentation , I find it inconsistent that sometimes I'm allowed to use symbols and sometimes I'm required to use only strings.

From the docs, you can query using symbols:

Conversation.where(status: [:active, :archived])
Conversation.where.not(status: :active)

But you can't compare using symbols:

conversation = Conversation.new(status: :active)
conversation.status # "active"
conversation.status == :active # false

And you can set the status using a symbol, but reading it back will return a string, so you must always use strings to compare:

conversation.status = :active # :active
conversation.status # "active"

My point is: I wished to use only symbols, because performance, and it feels more idiomatic to me. If enums are defined using symbols, and can be queried using symbols, why should I be forced (and have to remember!) to use strings when comparing something like conversation.status == "active" ?

My idea is to override getter:

def status
  super.try(:to_sym)
end

This way, I can always use symbols. Any reasonable reason for not doing this?

But you can't compare using symbols:

conversation = Conversation.new(status: :active)
conversation.status # "active"
conversation.status == :active # false

You dont need to compare with symbols:

conversation.active? # true

Any reasonable reason for not doing this?

Yes, you should use the library methods and modules instead of writing you own untested and excess code.

No need to compare enum with string or integer. DOC Link

conversation = Conversation.new(status: :active)
conversation.active? #true/false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM