Question

Using nanoc to create a blog archive page, I'd like to display a list similar to what's shown at http://daringfireball.net/archive/

I'm running into problems based on the way blog articles in nanoc are dated. Here's the code I've tried:

by_yearmonth = @site.sorted_articles.group_by{ |a| [a.date.year,a.date.month] }
by_yearmonth.keys.sort.each do |yearmonth|
    articles_this_month = by_yearmonth[yearmonth]
    # code here to display month and year
    articles_this_month.each do |article|
        # code here to display title of blog post
    end
end

nanoc doesn't seem to understand a.date.year or a.date.month -- when I try to compile the site, I get an error saying that the "date" method is undefined.

Was it helpful?

Solution

Update: Here's the code that ended up working, thanks to some crucial direction from ddfreyne:

# In lib/helpers/blogging.rb:
def grouped_articles
  sorted_articles.group_by do |a|
    [ Time.parse(a[:created_at]).year, Time.parse(a[:created_at]).month ]
  end.sort.reverse
end

# In blog archive item:
<% grouped_articles.each do |yearmonth, articles_this_month| %>
    <h2>Year <%= yearmonth.first %>, month <%= yearmonth.last %></h2>
    <% articles_this_month.each do |article| %>
        <h3><%= article[:title] %></h3>
    <% end %>
<% end %>

Thanks!

OTHER TIPS

Your question is missing a question. :)

You are almost there. I believe the code you’ve pasted correctly divides the articles into year/month. Now you need to display them. You can do that with ERB or with Haml (some people prefer the former, others prefer the latter). For example, with ERB:

# somewhere in lib/ (I propose lib/helpers/blogging.rb)
require 'date'
def grouped_articles
  sorted_articles.group_by do |a|
    [ Date.parse(a[:date].year, Date.parse(a[:date]).month ]
  end.sort
end

# in your blog archive item
<% grouped_articles.each_pair do |yearmonth, articles_this_month| %>
    <h1>Year <%= yearmonth.first %>, month <%= yearmonth.last %></h1>
    <% articles_this_month.each do |article| %>
        <h2><%= article[:title] %></h2>
    <% end %>
<% end %>

I haven’t tested it, bu that is the gist of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top