I have this code in my view in a rails4 blog app. It really looks ugly can somebody help me on how I can make it into a helper if that is possible.
<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 %>
I'm pretty sure someone can make it much better than this or if it's the best way of doing it, but here's some things you could do. You can extract the middle part into a helper method.
So now your view would look like this.
You can remove this line
<% @posts = BlogNgin::Post.order('created_at DESC') %>
and set it in your controller action as@posts = BlogNgin::Post.order('created_at DESC')
Not sure if you can change this into a scope to do something like @posts =BlogNgin::Post.desc
You can also shift the last part to another helper method as follows I'm not too sure if you can directly use the link_to method in the helper file but I think it should work.
So your view would look this (hopefully)