Simple page-view counter (Ruby on Rails)
This week we have built an online bookstore using Ruby on Rails. One of the components of this challenge was to implement a page view counter and this is the easiest way I found to do this.
The gem I used is called ‘Punching Bag’, I chose this gem because it looked simple to use and the docs are very straightforward.
Once you add gem "punching_bag"
to your Gemfile and bundle install
, all you need to do is run rails g punching_bag
and then rails db:migrate.
To use the gem, you need to add acts_as_punchable
to your model, in my case it was called Book, as we want to measure how many hits each book gets.
In your controller (books_controller.rb), add the following code or equivalent in the action that you want to keep track of, in my case the show page for each individual book:
class BooksController < ApplicationController
def show
@book.punch(request)
end
end
Now in your view you can add something along the lines the following code:
Number of views: <%= @book.hits %>
In the docs you can find a whole range of other helpers to find views in certain time ranges, sorting books by number of views, etc.
Simples!