Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reading_time filter/helper #150

Merged
merged 1 commit into from
Oct 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions bridgetown-core/lib/bridgetown-core/filters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,14 @@ def number_of_words(input)
input.split.length
end

# Calculates the average reading time of the supplied content.
# @param input [String] the String of content to analyze.
# @return [Float] the number of minutes required to read the content.
def reading_time(input, round_to = 0)
wpm = @context.registers[:site].config[:reading_time_wpm] || 250
(number_of_words(input).to_f / wpm).ceil(round_to)
end

# Join an array of things into a string by separating with commas and the
# word "and" for the last one.
#
Expand Down
11 changes: 11 additions & 0 deletions bridgetown-core/test/test_filters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,17 @@ def select; end
assert_equal 7, @filter.number_of_words("These aren't the droids you're looking for.")
end

should "reading_time filter" do
assert_equal 3, @filter.reading_time("word " * 551)

new_wpm_filter = make_filter_mock(
"reading_time_wpm" => 300
)

assert_equal 2, new_wpm_filter.reading_time("word " * 551)
assert_equal 1.84, new_wpm_filter.reading_time("word " * 551, 2)
end

context "normalize_whitespace filter" do
should "replace newlines with a space" do
assert_equal "a b", @filter.normalize_whitespace("a\nb")
Expand Down
9 changes: 9 additions & 0 deletions bridgetown-website/src/_data/bridgetown_filters.yml
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,15 @@

#

- name: Reading Time
description: Returns the average number of minutes to read the supplied content. Based on 250 WPM but that can be changed using the <code>reading_time_wpm</code> configuration variable. You can also pass an argument to specify which decimal point to round to (defaults to 0 for no decimals).
examples:
- input: "{{ page.content | reading_time }} minutes"
output: "4 minutes"
- input: "{{ page.content | reading_time: 1 }} minutes"
output: "3.2 minutes"
#

- name: Array to Sentence
description: >-
Convert an array into a sentence. Useful for listing tags.
Expand Down