Skip to content

Instantly share code, notes, and snippets.

@dsprenkels
Created June 21, 2017 12:57
Show Gist options
  • Save dsprenkels/3dfff4d8176bd8fab1831567b6789bed to your computer and use it in GitHub Desktop.
Save dsprenkels/3dfff4d8176bd8fab1831567b6789bed to your computer and use it in GitHub Desktop.
A reading time filter for Jekyll templates
# A reading time filter for Jekyll templates
#
# Author: Daan Sprenkels <hello@dsprenkels.com>
#
# This module implements a filter for post content which calculates a range of
# time to display to the user. The filter is made for English text (and will
# display an English message). However, you can modify this script for your
# personal needs.
module ReadingTimeFilter
def reading_time(input)
# Define your personal parameters here
text_words_per_minute_lo = 400
text_words_per_minute_hi = 200
code_lines_per_minute = 20
# Split the post into text and code
text = input.gsub(/<code>.*?<\/code>/im, "")
text_words = text.split.size
code_lines = input.lines.size - text.lines.size
# Calculate the time that a user needs for reading your post
code_minutes = code_lines / code_lines_per_minute
lo_minutes = text_words / text_words_per_minute_lo + code_minutes
hi_minutes = text_words / text_words_per_minute_hi + code_minutes
avg_minutes = (lo_minutes + hi_minutes) / 2
# Either show the average, or a duration range
if avg_minutes >= 10
"#{lo_minutes.round} – #{hi_minutes.round} minute read"
else
"#{avg_minutes.round} minute read"
end
end
end
Liquid::Template.register_filter(ReadingTimeFilter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment