EvanRPavone
Posted on May 13, 2021
Introduction
Having a view counter is a common thing when it comes to blog posts, tutorials, videos, etc... I wanted to have a view counter for a simple blog post app. I did some quick googling and found out about a gem called punching_bag. It is a very easy gem to use, I will be saying that a lot. Let's get started on showing you how to have a simple view counter for your rails application.
Installing Punching Bag
Installing this gem is very easy to do. It all starts with you adding the gem to your gemfile:
gem “punching_bag”
After you have the gem in your gemfile you will need to run three commands in your terminal:
To start off, you need to run bundle install
as usual. After you run bundle you need to run the generator for punching_bag:
rails g punching_bag
This will generate a table in your database called punches, which means you need to run rails db:migrate
.
Once you got your database migrated, go into your Post Model and add this line of code:
acts_as_punchable
Adding this will allow you to get the amount of hits/views on your posts. One last step, and that is to go into your PostController under the show method and have a punch with a request like so:
@post.punch(request)
Congrats you have successfully installed punching_bag and configured it to work with your views. Sweet, let’s add a view counter to your views.
The Views
Using the gem in your views is very simple as well. To be honest, using the gem is very simple. For you to see a view counter in your views you need to call the hits like so:
Views: @post.hits
That’s it you can now see how many views a Post has. That’s it, simple right? If you want to have your index for the posts to show the most viewed post at the top, that would be in your controller under the index method:
@posts = Post.most_hit
Now on your index posts page you can see that the post with the most views will be at the top. It’s like adding a scope but the punching bag gem already does that for you.
Conclusion
The punching bag gem is easy to use and works like a charm. Personally, using this gem is the best way to show views. I hope this helped you for your application. If you need any more information about the gem please visit the github link, Punching Bag.
Posted on May 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.