Page Views counter sinatra?

北慕城南 提交于 2019-12-24 21:41:41

问题


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!


回答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?




回答2:


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


来源:https://stackoverflow.com/questions/29708416/page-views-counter-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!