require 'cgi' module Plate # Various view helpers related to blogging. Tags, categories, archives and the like. module BloggingHelper # Returns a customized hash of post archives for the given category def category_archives(category) result = {} posts.archives.keys.each do |year| posts.archives[year].keys.each do |month| posts.archives[year][month].keys.each do |day| posts.archives[year][month][day].each do |post| if post.category == category result[year] ||= {} result[year][month] ||= {} result[year][month][day] ||= [] result[year][month][day] << post end end end end end result end # Escape markup for use in XML or HTML def html_escape(text) ::CGI.escapeHTML(text) end alias_method :xml_escape, :html_escape # Grab the next blog post. # # Returns nil if this is the last post. def next_post return nil if post_index < 0 or post_index >= post_count @next_post ||= self.posts[post_index + 1] end # Grab the post previous to this one. # # Returns nil if this is the first post. def previous_post return nil if post_index < 1 @previous_post ||= self.posts[post_index - 1] end # The total number blog posts def post_count @post_count ||= self.posts.length end # Returns a number of where this post is in all posts def post_index @post_index ||= self.posts.index(self.post) end # Find all posts for the given category def posts_for_category(category) self.posts.select { |p| p.category == category } end # Find all posts for the given year, month and optional category. def posts_for_month(year, month, category = nil) result = [] if months = self.posts.archives[year.to_s] if month = months[month.to_s] month.each_value do |day| result << day.select { |post| category == nil or post.category == category } end end end result.flatten end # Find all posts for the given year and optional category. def posts_for_year(year, category = nil) result = [] if months = self.posts.archives[year.to_s] months.each_value do |month| month.each_value do |day| result << day.select { |post| category == nil or post.category == category } end end end result.flatten end def years_for_category(category) result = [] self.posts.archives.keys.each do |year| if posts_for_year(year, category).size > 0 result << year end end result.sort end end end