Adding reading time to your post image

Adding reading time to your post

Author: Charli

Jan 29, 2019 - Reading time: 2 min

Adding a reading time calculation to your rails app is pretty straight forward.
In my example i create it as a shared method across multiple models.
If you only want to add it to your blog post, you can get away with adding the method to your blog.rb file.

First off, create a content_util.rb file under models/concerns

Since its a shared method between content (blog, guides and resources) this is where it belongs.
If you only have 1 model, you can just add it under that current model.

module ContentUtil
  extend ActiveSupport::Concern

  def reading_time(text)
    (text.split.size / 180.0).ceil


The method takes 1 argument, text. Then the split.size method is called on the string or text, which split up the words and counts them. They are divided by 180, which is the average number of words a human reads. Some says it's more, but for technical articles its a good fit.
The .ceil method will return the smallest integer greater or equal to the float.

So what happens is that it will return a clean number, like 5 or even 1 if its a short post.

Inside the models where you want to use the method, include the module

  include ContentUtil

And you can now call the method in your view like this:

<%= item.reading_time(item.body) %>