Having built a blog, I wanted the user to be able to preview 4 blog entries on the landing page. Not wanting to hard code the article paths, I wanted the code to automatically pull the four most recent posts. Some very simple Ruby methods to the rescue.
First, I wanted to list the four most recent entries, sorted from the oldest to the most recent, from the database of my blog entries. I also wanted to have flexibility in the number of blog posts shown in case I changed the layout later. The following helper method, placed as a module in the home page helper folder, does the trick. The ruby fetch method returns the element at the given index position.
module HomeHelper def article_helper(index) @articles = Article.order('created_at DESC').first(4) @article = @articles.fetch(index) end end
Then I pass the above method as an argument to the Rails article_path method embedded in a Rails link_to tag.
<%= link_to "Read more", article_path(article_helper(0)), class: "btn btn-info" %>
For each of the four blog previews, I change the article_helper argument to the appropriate index position.
I also wanted to pull the blog post title for display in a jQuery dropdown. I simple call the blog post title attribute.
def blog_title(index) @articles = Article.order('created_at DESC').first(4) @article = @articles.fetch(index) @article.title end
Finally, I wanted a blog post text preview. I pass the blog post text attribute to the truncate method , limiting the preview to 100 characters and making sure that no word is clipped by adding the separator option. The strip_tags method is peculiar to the way I post my blog entries and can be ignored.
def blog_text_teaser(index) @articles = Article.order('created_at DESC').first(4) @article = @articles.fetch(index) truncate(strip_tags(@article.text), length: 100, separator: " ") end
Here are the three methods on the home page, which I nested within a jQuery dropdown animation.
<%= blog_title(0) %> <%= blog_text_teaser(0)%> <%= link_to "Read more", article_path(article_helper(0)), class: "btn btn-info" %>