在视图之外重构代码
我有以下视图代码,它显示事件,以及通知用户今天、昨天或过去一周是否发生以下事件的标题。
一切都工作正常,但我更愿意将其重构到视图之外,我不能将其放入助手中,因为它需要在循环迭代之间维护变量状态。知道如何整理这个吗?谢谢
<% displayed_week_already = false %>
<% displayed_yesterday_already = false %>
<% displayed_today_already = false %>
<% @events.each do |event| %>
<%= event.title &>
<% if (Time.now - 1.week) > event.created_at && !displayed_week_already %>
<% displayed_week_already = true %>
Events in past week
<% elsif (Time.now - 1.day) > event.created_at && (Time.now - 2.day) < event.created_at && !displayed_yesterday_already %>
<% displayed_yesterday_already = true %>
Events yesterday
<% elsif (Time.now - 1.day) < event.created_at && !displayed_today_already %>
<% displayed_today_already = true %>
Events in past day
<% end %>
<% end %>
预期输出为:
过去一天的事件
约翰创建了一篇新文章
Dan 对第 1 条的评论
苏删除了文章 2
昨天的事件
Sue 创建了一篇新文章
过去一周的活动
卡罗尔升职
丹发表了一篇新文章
I have the following view code which displays events, along with headers informing the user if the following events occured today, yesterday, or in the past week.
It all works fine, but I would prefer to refactor it out of the view, I can't put it in a helper because it needs to maintain the variables state between loop iterations. Any idea how to tidy this up? thanks
<% displayed_week_already = false %>
<% displayed_yesterday_already = false %>
<% displayed_today_already = false %>
<% @events.each do |event| %>
<%= event.title &>
<% if (Time.now - 1.week) > event.created_at && !displayed_week_already %>
<% displayed_week_already = true %>
Events in past week
<% elsif (Time.now - 1.day) > event.created_at && (Time.now - 2.day) < event.created_at && !displayed_yesterday_already %>
<% displayed_yesterday_already = true %>
Events yesterday
<% elsif (Time.now - 1.day) < event.created_at && !displayed_today_already %>
<% displayed_today_already = true %>
Events in past day
<% end %>
<% end %>
Expected output would be:
Events in past day
John created a new artice
Dan commented on article 1
Sue deleted article 2
Events yesterday
Sue created a new article
Events in past week
Carol was promoted
Dan cerated a new article
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可能会做类似以下的事情。我省略了模型本身定义的实现方法。
现有视图
_events.html.erb
app/helpers/event_display_helper.rb
I might do something like the following. I am leaving out the implemented methods defined on the model itself.
existing view
_events.html.erb
app/helpers/event_display_helper.rb
您可以使用命名范围轻松地在模型中执行此操作(我假设使用 Rails 3,因为这是我最了解的)。您需要自己定义它们,但它们非常简单。
然后只需迭代您视图中的每个组即可。应该让它变得更干净,你不需要那么多逻辑,因为它是它真正所属的地方。
You could easily do this in the model, with named scopes (I'm assuming Rails 3 because that's what I know best). You'll need to define them yourself but they're pretty simple.
Then just iterate over each of the groups in your view. Should make it a lot cleaner and you won't need so much logic, as it's where it actually belongs.