Skip to content

Commit 4344171

Browse files
committed
Add reading time to blog posts
1 parent 76afbe3 commit 4344171

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

_layouts/post.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,9 @@ <h1>{{ page.title }}</h1>
8989
<span>Published on</span>
9090
<span class="date">{{ page.date | date: "%Y-%m-%d" }}</span>
9191
</div>
92+
<div class="publishedinfo">
93+
<span>Reading time: {{ content | reading_time }}</span>
94+
</div>
9295
{% endif %}
9396
</div>
9497
</div>

_plugins/reading_time_filter.rb

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
module ReadingTimeFilter
2+
include Liquid::StandardFilters
3+
4+
def reading_time(input)
5+
# Get words count.
6+
total_words = get_plain_text(input).split.size
7+
8+
# Load configuration.
9+
config = @context.registers[:site].config["reading_time"]
10+
11+
# Setup default value.
12+
if ! config
13+
second_plural = "seconds"
14+
minute_singular = "minute"
15+
minute_plural = "minutes"
16+
else
17+
second_plural = config["second_plural"] ? config["second_plural"] : "seconds"
18+
minute_singular = config["minute_singular"] ? config["minute_singular"] : "minute"
19+
minute_plural = config["minute_plural"] ? config["minute_plural"] : "minutes"
20+
end
21+
22+
# Average reading words per minute.
23+
words_per_minute = 150
24+
25+
# Calculate reading time.
26+
case total_words
27+
when 0 .. 74
28+
return "30 #{second_plural}"
29+
when 75 .. 149
30+
return "1 #{minute_singular}"
31+
else
32+
minutes = ( total_words / words_per_minute ).floor
33+
return "#{minutes} #{minute_plural}";
34+
end
35+
end
36+
37+
def get_plain_text(input)
38+
strip_html(strip_pre_tags(input))
39+
end
40+
41+
def strip_pre_tags(input)
42+
empty = ''.freeze
43+
input.to_s.gsub(/<pre(?:(?!<\/pre).|\s)*<\/pre>/mi, empty)
44+
end
45+
end
46+
47+
Liquid::Template.register_filter(ReadingTimeFilter)

0 commit comments

Comments
 (0)