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!
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!
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?
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")