2013-08-19 60 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)) %>