Permalink
Browse files

first attempt at post word counts

  • Loading branch information...
johlym committed Dec 15, 2015
1 parent d6b48c3 commit 004b155426b3cd8cb08316c7e6941562baa1075d
Showing with 64 additions and 0 deletions.
  1. +8 −0 _layouts/default.html
  2. +56 −0 _plugins/posts-word-count.rb
@@ -36,3 +36,11 @@ <h3 class="masthead-title">

</body>
</html>
<!--
***BLOG STATS***
Total number of words in this blog: {% posts_word_count total %}
Average number of words per post: {% posts_word_count average %}
The longest post in this blog has {% posts_word_count longest %} words.
-->
@@ -0,0 +1,56 @@
# {% posts_word_count %}
# Output some interesting word-count stats for your posts.
#
# To install, copy this file into your Jekyll/Octopress plugins folder
# To use: {% posts_word_count PARAM %}
#
# PARAM can be:
# total (total word count of all posts)
# average (average word count across all posts)
# longest (longest word count of any post)
# longest_post_index (index in site.posts of longest post)

class PostsWordCount < Liquid::Tag
def initialize(tag, text, tokens)
@total_word_count = 0
@average_word_count = 0
@longest_word_count = 0
@longest_post_index = 0
@tag = tag
@text = text.strip
@tokens = tokens
end

def render(context)
the_result = nil
all_posts = context.registers[:site].posts # OLDEST first!
all_posts.each_with_index { |this_post, index|
num_words = word_count(this_post.content)
@total_word_count += num_words
if num_words > @longest_word_count
@longest_word_count = num_words
@longest_post_index = all_posts.count - (index + 1)
end
}
@average_word_count = @total_word_count / all_posts.count

if @text.start_with? "total"
the_result = @total_word_count
elsif @text.start_with? "average"
the_result = @average_word_count
elsif @text.start_with? "longest_post_index"
the_result = @longest_post_index
elsif @text.start_with? "longest"
the_result = @longest_word_count
end

return the_result
end

def word_count(string)
# Simplistic, but agrees with Jekyll's number_of_words filter.
return string.scan(/\S+/).count
end
end

Liquid::Template.register_tag('posts_word_count', PostsWordCount)

0 comments on commit 004b155

Please sign in to comment.