Search code examples
rubyblogsnanoc

Using nanoc to create a list of blog articles, sorted by month and year


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.


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!