-1

How to implement a page views counter in Sinatra and Ruby?

I have tried the @@ variables but they reset to zero whenever the page is loaded...

Like this one: http://148.251.142.233:8080/

Thanks!

Asad Awadia
  • 1,417
  • 2
  • 9
  • 15
  • Add an additional field "counter" to your page object in DB. Update it with +1 on every request for that page. – Lukas Valatka Apr 17 '15 at 21:39
  • What do you mean by page object in DB? – Asad Awadia Apr 17 '15 at 22:27
  • Where do you keep your page data? Are they static or dinamic (populated by the data from database fields)? If they are static, you have to store the views count somewhere in files in the application. It would be ugly, but you could use file open and save everytime the user asks for the page and keep the views count in that specific file. Does this answer your question? – Lukas Valatka Apr 18 '15 at 09:31

2 Answers2

1

I think your problem is that you cant store global variable in sinatra as usual. You need to store page views count data in setting like this

set :my_config_property, 'hello world'

Here is docs about it http://www.sinatrarb.com/configuration.html SO question about it In Sinatra(Ruby), how should I create global variables which are assigned values only once in the application lifetime?

Community
  • 1
  • 1
Pavel
  • 47
  • 2
  • 10
1

Just storing the value in memory will not be enough because your application server will probably be serving request with different processes and every process will have a different copy of the class variables. Even if that work when the server is reset you will lose the counter value anyway.

I would use a specialized database like Redis. It's very fast and easy to do what you want. You just use something like this:

require "redis"
redis = Redis.new
total_pageviews = redis.incr("page_counter")
Dimas Kotvan
  • 723
  • 1
  • 7
  • 10