1

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.

alt0
  • 21
  • 5

2 Answers2

1

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!

alt0
  • 21
  • 5
0

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.

Denis Defreyne
  • 2,213
  • 15
  • 18
  • Thanks very much for responding (and for making and supporting such a cool web authoring tool!). I should have clarified that I do understand how to get the results to display, I just left them out of the above code for the sake of brevity. My problem with the code in either of the above examples is that I can't make it give me the results in the first place! When I try to compile I get the error "NoMethodError: undefined method `date' for #". So I figure that nanoc must want a different method of parsing the date, but I have no idea what that would be. Thanks again! – alt0 Mar 05 '12 at 22:27
  • Ahh, my mistake. a.date won’t work; to access attributes you need a[:date]. Since it is a string, Date.parse should be used. I’ve updated my code snippet. – Denis Defreyne Mar 07 '12 at 06:58