[英]Ruby on Rails style: Model#attr_name? method
My Person model has a vip
attribute backed by ActiveRecord, so it's got vip
and vip=
methods automatically. My Person模型具有ActiveRecord支持的
vip
属性,因此它会自动获得vip
和vip=
方法。 This attribute was initially a boolean, but needs to change to an integer to allow for several categories of importance/prestige/etc, and since there are already many references to the boolean value, I thought I'd add a method like: 这个属性最初是一个布尔值,但是需要更改为整数以允许几个类别的重要性/信誉/等,并且由于已经有很多对布尔值的引用,我想我应该添加一种方法:
class User < ActiveRecord::Base
def vip?
self.vip >= 10
end
end
So I could fix existing calls to #vip
with calls to #vip?
因此,我可以将现有的对
#vip
的呼叫修复为对#vip
的呼叫#vip?
. 。 Is it bad practice, or just confusing to do it like this, with
#vip
storing the level of importance and vip?
#vip
存储重要性和vip?
级别是不好的做法,还是只是令人困惑vip?
checking whether a record is "important enough"? 检查记录是否“足够重要”? The naming is a little tangled because
status
is already taken by another column. 命名有点纠结,因为
status
已由另一列获取。
I think you're on the right track with renaming the attribute. 我认为重命名属性是正确的。
vip?
returns whether the attribute in question exceeds a certain value. 返回所讨论的属性是否超过某个值。 Maybe the attribute should be something like
credits
, points
, or reputation
? 也许属性应该是
credits
, points
或reputation
? I think of something like StackOverflow itself in this regard. 在这方面,我想到了类似StackOverflow的东西。 Users have a cumulative
reputation
score. 用户具有累积的
reputation
得分。 Some badges are assigned based simply on this cumulative score. 某些徽章仅基于此累积分数进行分配。 While this is likely a composite score of all the up votes, questions, answers, etc. a user has received, your data might be a simple integer value from which you can base status.
虽然这很可能是用户收到的所有赞成票,问题,答案等的综合评分,但您的数据可能是一个简单的整数值,您可以以此为基础建立状态。 vBulletin and other forum software also have this based on the number of posts and other attributes.
vBulletin和其他论坛软件也基于帖子数量和其他属性来具有此功能。
A predicate method
should return true
or false
, but you can stablish the condition that you want. predicate method
应返回true
或false
,但是您可以稳定所需的条件。 Regardless of the method name, I think what you have done is right. 不管方法名称如何,我认为您所做的都是正确的。
class User < ActiveRecord::Base
def vip?
vip >= 10 # self is unnecesary
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.