Rails Creating A view helper

95 views Asked by At

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 %>
1

There are 1 answers

0
Althaf Hameez On BEST ANSWER

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.

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

So now your view would look like this.

<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 %>

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.

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

So your view would look this (hopefully)

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