【问题标题】:Rails: Nil checking a method chain best practicesRails:Nil 检查方法链最佳实践
【发布时间】:2016-04-09 16:44:25
【问题描述】:

给定以下方法。当comment.story.teams.first 的结果可能是nil 时,如何最好地使这段代码安全?

我已经尝试过comment.story.teams.first.try(:users),但随后这就把罐子踢到了路上,分配users -= [@current_user] 引发了undefined method 错误。

  def recipients
    if comment.commentable_type == "Story"
      users = comment.story.teams.first.users
    else
      users = comment.other_commenters + [comment.commentable_user]
    end
    users -= [@current_user]
    users.uniq
  end

我可以在这里使用更好的模式吗?

【问题讨论】:

  • 如果你没有想到这一点(不是想侮辱你的智力):(users || []) -= [@current_user] 或者早点做users = comment.story.teams.first.try(:users) || []
  • 从不侮辱。就像我经常做的那样,在切换语言时对最佳实践感到困惑。这很好用。谢谢。

标签: ruby-on-rails ruby null try-catch method-chaining


【解决方案1】:

只需在 ruby​​ 的除非语句中包含您需要检查的任何内容。

unless comment.story.teams.first.nil?
   ##Execute code in here
end

希望对您有所帮助。重组方法中的某些语句可能更容易。 'Unless' 只是 'if not' 的 ruby​​ 语法。

【讨论】:

    猜你喜欢
    • 2011-09-06
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多