简体   繁体   English

Ruby on Rails样式:Model#attr_name? 方法

[英]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属性,因此它会自动获得vipvip=方法。 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 ? 也许属性应该是creditspointsreputation 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应返回truefalse ,但是您可以稳定所需的条件。 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.

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