简体   繁体   English

我应该如何重构这个有条件的助手?

[英]How should I refactor this conditional helper?

What I want to achieve is a label that shows how many comments there are on a page. 我要实现的是一个标签,该标签显示页面上有多少条评论。 Currently the code works to show what I need, but I believe this is not the right way and could use some refactoring. 当前代码可以显示我的需求,但是我认为这不是正确的方法,可以使用一些重构。

Also, should I move the h1 tag out into the view instead or is content_tag acceptable? 另外,我应该将h1标签移到视图中还是可以接受content_tag

What I need is basically to put "Be the first to comment" if there are no comments and pluralize the label if there are comments. 我基本上需要的是,如果没有评论,则放置“成为第一个评论者”,如果有评论,则使标签多元化。

Thanks for your help on this. 感谢您的协助。

   def number_of_comments
     @review.comments.count
   end

   def render_comments_count
      if number_of_comments == 0
        content_tag(:h1, "Be the first to comment")
      elsif number_of_comments  == 1
        content_tag(:h1, "1 comment")
      else
        content_tag(:h1, number_of_comments) + content_tag(:h1, "comments")
      end
     end
   end

You can use pluralize and extract the h1 to the view: 您可以使用复数形式并将h1提取到视图中:

def number_of_comments
  @review.comments.count
end

def render_comments_count
  if number_of_comments.zero?
    'Be the first to comment'
  else
    "#{number_of_comments} #{'comment'.pluralize(number_of_comments)}"
  end
end

Then, in the view: 然后,在视图中:

<h1><%= render_comments_count %></h1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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