开发者

Refactoring code out of the view

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 && !displaye开发者_如何学God_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


I might do something like the following. I am leaving out the implemented methods defined on the model itself.

existing view

<%= render "events", :title => "Events in past day",  :events => from_today(@events) %>
<%= render "events", :title => "Events yesterday",    :events => from_yesterday(@events) %>
<%= render "events", :title => "Events in past week", :events => from_this_week(@events) %>

_events.html.erb

<% if events.present? %>
  <%= title %>
  <% events.each do |event| %>
    <%= event.title %>
  <% end %>
<% end %>

app/helpers/event_display_helper.rb

module EventDisplayHelper
  def from_today(events)
    events.select{|x| x.happened_today?}
  end

  def from_yesterday(events)
    events.select{|x| x.happened_yesterday?}
  end

  def from_this_week(events)
    events.select{|x| x.happened_this_week_before_yesterday?}
  end
end


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.

@last_week = @event.last_week
@yesterday = @event.yesterday
@today = @event.today

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜