Showing Estimated Reading Time On A Rails Blog Post

Alexander Paterson
|
Posted almost 7 years ago
|
1 minute
Showing Estimated Reading Time On A Rails Blog Post
If your articles contain HTML, there's an extra step to calculating a word count

For this blog, I added a method to my post model that uses nokogiri (a dependency of rails) to extract the inner text of the post content so that the words can be counted and turned into an estimated reading time.

class Post < ActiveRecord::Base

...

##########################
# => Methods
##########################
  def reading_time
    words_per_minute = 150
    text = Nokogiri::HTML(self.content).at('body').inner_text
    (text.scan(/\w+/).length / words_per_minute).to_i
  end

...

end

Now in my templates, I can simply render out this value while using the rails pluralize helper so that it can display both "1 minute" and "n minutes":

<div class="wordcount">
  <i class="fa fa-clock-o"></i>
  <span><%=pluralize(@post.reading_time, 'minute')%></span>
</div>

That <i class="fa fa-clock-o"></i> is a fontawesome clock glyph provided by the font-awesome-rails gem. For good measure, here's the CSS I'm currently using to style the estimated reading times on my articles.

.wordcount {
  align-items: center;
  border: 1px solid $light-grey;
  border-radius: Calc((0.65rem + 0.5rem + 8px) / 2);
  display: flex;
  font-size: 0.65rem;
  justify-content: center;
  padding: 0.25rem 0.4rem;
  i {
    font-size: 0.8rem;
    margin-right: 0.25rem;
    padding-top: 0.15rem;
  }
}


-->
ALEXANDER
PATERSON