此用户方法参数是否已命名?

时间:2016-03-28 19:02:32

标签: ruby-on-rails ruby ruby-on-rails-4

我有一种方法来检查用户是否可以编辑我的Rails应用程序上的帖子或评论。因为用户可以拥有这两种类型的实体,所以我决定将此方法作为参数post_or_comment

class User < ActiveRecord::Base
  def can_edit?(post_or_comment)
    post_or_comment.user == self || self.admin?
  end
end

这是一个很好的做法,不明确地将这样的任何对象作为参数,并且我为参数选择的名称是否有意义?

我对像CanCan这样复杂的用户角色处理程序不感兴趣,因为我正在学习,宁愿保持简单。

1 个答案:

答案 0 :(得分:1)

如果理解在你的模式中,帖子是一种评论,反之亦然,那么以一种或另一种形式表达它并不是真的令人困惑,暗示它同样适用于这两种类型。

一般来说,除非你有充分的理由,否则最好避免过度限制。有一种方法可以将你非常具体的方法变成一个可能在大多数情况下工作的方法,如果不是,那是因为你把它传递给了一个无主的东西:

def can_edit?(thing)
  # Admin can edit anything.
  return true if (admin?)

  case (thing)
  when User
    # Users can edit themselves
    thing === self
  else
    if (thing.respond_to?(:user))
      # If the owner matches.
      thing.user === self
    else
      # Don't really know, so say no by default.
      false
    end
  end
end

此代码的最坏情况失败状态是它说“不”。现在你可以传递任意可能有或没有user属性的东西,它会按预期工作。对于其他特殊情况,您可以向主when添加另一个case