Helper for generating a monthwise list

2 views
Skip to first unread message

Leslie Viljoen

unread,
Apr 17, 2011, 12:00:49 AM4/17/11
to Webby
This is my helper for generating the list of articles sorted by month
on the right sidebar of my site (http://www.lesismore.co.za).

It takes parameters for css classes to be used for each component of
the list and uses a meta data attribute called "yearmonth" for the
date. This must look like:
- yearmonth: 2011-02

It makes use of a page's "title" attribute too.

I use it in my layout like so:
<%= monthwise('year', 'month', 'entrylist') %>

The helper goes in a file called monthwise.rb in the lib directory.

module MonthwiseHelper
def monthwise(year_css_class, month_css_class, title_css_class)
years = Hash.new{|k, v| k[v] = Hash.new{|l, w| l[w] = []}}

dated = @pages.find(:all) do |page|
page._meta_data.has_key?("yearmonth")
end

dated.each do |res|
year, month = res.yearmonth.split('-').map{|x|x.to_i}
link, title = res.url, res.title
years[year][month] << [link, title]

end

html = ""
years.sort.reverse.each do |year, months|
html += %Q[<p class="#{year_css_class}">#{year}</p>]
months.sort.reverse.each do |month, links|
links.sort!{|a, b| a[1] <=> b[1]}
links.map!{|lt| link, title = lt; %Q[<li><a
href="#{link}">#{title}</a></li>] }
month_name = Date::MONTHNAMES[month]
html+=<<EOF
<p class="#{month_css_class}">#{month_name}</p>
<div class="#{title_css_class}">
<ul>
#{links}
</ul>
</div>
EOF
end
end

html
end
end

Webby::Helpers.register(MonthwiseHelper)

Reply all
Reply to author
Forward
0 new messages