[英]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. 查看ActiveRecord的Enum 文档 ,我发现不一致的是,有时允许我使用符号,有时只需要使用字符串。
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"
? 如果枚举是使用符号定义的,并且可以使用符号查询,那么在比较诸如
conversation.status == "active"
类的内容时,为什么我必须(必须记住!)使用字符串?
My idea is to override getter: 我的想法是重写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. 是的,您应该使用库的方法和模块,而不要编写自己的未经测试的多余代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.