开发者

Knowing when a new session starts in Rails

开发者 https://www.devze.com 2023-03-07 18:43 出处:网络
I\'ll start by describing a scenario, I\'m open to other ways of doing this but I can\'t think of any other ways.

I'll start by describing a scenario, I'm open to other ways of doing this but I can't think of any other ways.

I have anonymous users on a Rails 2 application. When a new user comes to the site, I'd like to place a cookie saying "I've visited the site 1 time" and record this in our system. The user leaves and comes back a month later I read this cookie, increment the number of visits ("I've been here 2 times") and record this in our system.

My plan:

When a new session starts

  • if the user is new - create the cookie, log visit
  • if the user is returning - read cookie, increment value, write cookie, log visit

Where I'm stuck right now is at the "When a new session starts" step. If you have a .net background what I'm looking for is the equivalent of Session_Start in ASP.NET. I could query the database on every request and check to see if a particular session id has alrea开发者_如何学JAVAdy been logged, but that seems inefficient.


Actually it's a bad idea. Rails stores the session in the db or in the file system (tmp/sessions). If you want to know, if the user was on the page before, you just don't delete the sessions (no session expire). But then the number of sessions will grow into infinity.

If a user returns on the same machine with the same browser, the session will be still there. In you're application / session controller you can do:

session[:visits] ||= 0
session[:visits] += 1

but then it will be incremented with every click. So if you want to just count the visits you need to store the last clicked time as well and just increment, if the user was away more than half an hour or so.

session[:visits] ||= 0
now = DateTime.now.to_i
session[:visits] += 1 if session[:last_click] && session[:last_click] < (now - 60*30)
session[:last_click] = DateTime.now.to_i

Still a bad idea, because if the user returns on different browser or computer, the counter would start again. (More about sessions: http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions)

0

精彩评论

暂无评论...
验证码 换一张
取 消