Add reading time to posts

How To Add Reading Time To Your Posts

January 12, 2015|Blog, Ruby

If you have a blog in Rails you can do all kinds of fun stuff with it like add a quick estimate for your users to show them how long it will probably take them to read your post.

If you, like me, have a Post model with a body attribute that contains the body of the post. Go to your post.rb file and add the following method:

def word_count

This simple method takes your Post model body attribute splits up every space and the size measures how many spaces there are, or in other words, how many words there are in the body.

The average person reads 180 words per minute on a monitor. So, now we just need to divide the total number of words by 180 to get our reading speed. To do so add the next method right below the word_count method in your post.rb file:

def reading_time
     (word_count / 180.0).ceil

What the reading_time method does is take the word_count of the body of your post and divides it by 180.0. This will result in a float in order to be more precise. If you had done (word_count / 180) this would result in an integer and you wouldn’t get a precise number. The ceil method is a ruby method that will return your float number into an integer. The integer is going to be greater than or equal to your float number.

Why add the ceil method at all? Let’s say you write a nice small article that ends up being 165 words. If you divide 165 by 180 you will get 0. In order to be more precise you decide to use floating numbers. So, you divide 165 by 180.0 and you get 0.9166666666. That is more precise. But, you don’t want to say: reading time 0.916666666 minutes. You want an integer. You want to say it’s basically going to take you a minute to read this article. That’s what the ceil method is going to do for you. It will round up to 1. So, reading_time will result in 1 when you have a post that is 165 words.

In order to use this method you just need to get the post available to you from the controller like so:

@post = Post.find(params[:id])

and then you can use @post.reading_time or even @post.word_count in your views.

Learn to Effortlessly Create Anything in CSS

Get access to my free courses, best articles, and tips once a week.

I won't send you spam, promise. If it ever feels that way you can unsubscribe at any time.

Sign Up For Free


Sign In