2013-08-19 61 views
0

我在rails4博客應用程序中查看了該代碼。它真的看起來很難看,有人可以幫助我如何在可能的情況下將它變成幫手。Rails創建視圖幫助程序

<h4>Archive</h4> 
<%# This is really awful. I know. %> 
<% @posts = BlogNgin::Post.order('created_at DESC') %> 
<% archive_array = [] %> 
<% @posts.each do |post| %> 
<% date = post.created_at.strftime("%m") + " " + post.created_at.strftime("%Y") %> 
<% if !archive_array.include? date %> 
<% archive_array << date %> 
<% end %> 
<% end %> 
<% archive_array.each do |date| %> 
<% date = date.split(' ') %> 
<%= link_to Date::MONTHNAMES[date[0].to_i].to_s + " " + date[1],  blog_ngin.root_path + date[1] + '/' + date[0] %><br /> 
<% end %> 

回答

0

我很確定有人可以做得比這更好,或者如果這是做這件事的最好方法,但這裏有一些事情可以做。您可以將中間部分提取到輔助方法中。

def archive(posts) 
    <% posts.each do |post| %> 
    <% archive_array = [] %> 
    <% date = post.created_at.strftime("%m") + " " + post.created_at.strftime("%Y") %> 
    <% if !archive_array.include? date %> 
     <% archive_array << date %> 
    <% end %> 
    <% end %> 
end 

所以現在你的看法看起來像這樣。

<h4>Archive</h4> 
<%# It's probably still awful %> 
<% @posts = BlogNgin::Post.order('created_at DESC') %> 
<% archive_array = archive(@posts) %> 
<% archive_array.each do |date| %> 
<% date = date.split(' ') %> 
<%= link_to Date::MONTHNAMES[date[0].to_i].to_s + " " + date[1],  blog_ngin.root_path + date[1] + '/' + date[0] %><br /> 
<% end %> 

您可以刪除此行<% @posts = BlogNgin::Post.order('created_at DESC') %>並設置它在你的控制器行動@posts = BlogNgin::Post.order('created_at DESC') 不知道,如果你能變成一個範圍,這樣做@posts此= BlogNgin::Post.desc

您也可以移最後一部分到另一個輔助方法如下我不太確定你是否可以直接在輔助文件中使用link_to方法,但我認爲它應該可以工作。

def links(archive_array) 
    MONTHNAMEs = #put your array here 
    <% archive_array.each do |date| %> 
    <% date = date.split(' ') %> 
    <%= link_to Date::MONTHNAMES[date[0].to_i].to_s + " " + date[1],  blog_ngin.root_path + date[1] + '/' + date[0] %> 
    <% end %> 
end 

所以你的觀點會看這個(希望)

<h4>Archive</h4> 
<%# It's probably still awful %> 
<%= links(archive(@posts)) %>