Rails 3: How do I know if a user has visited a page before?

I have a Rails application (using Authlogic for authentication) with a simple jquery animation that I want to run only once when the first page loads. I know that the key is to check cookies or something to see if the user has visited the page before. Please forgive my n00bness, I know little about HTTP cookies or sessions.

So, what is the best way to see if a visitor (even if they are not logged in) is viewing the page for the first time?

EDIT: Good, so I understand that I did not quite understand.

I spent hours on similar questions and read the Rails API Docs for cookies and sessions, and I still canโ€™t imagine how to implement the Visited function ? for each page of my site, it will be set to true only after the user visits the page for the first time. I looked at the alleged โ€œduplicatedโ€ Rails Detect If User Very First Visit question and the corresponding answers and still cannot understand.

Here is my "Pages" controller:

def home @title = "Home" end def contact @title = "Contact Us" end 

dd

And my jquery javascript that does a simple animation:

 $(document).ready(function() { if (!$.cookie('visited')) { $('.title .flying-text').css({opacity:0}); $('.title .active-text').animate({ opacity:1, marginTop: "-150px", }, 5000); } }); 

I want it to show if the user has visited before. I have no idea how to properly set a cookie in Rails, nor where to put it, and how to make sure that the animation script can access the same cookie value. Can someone give me a hand?

~ Dan

+4
source share
2 answers

You can set your cookie as follows:

 cookies[:welcomed] = {:value => true, :expires => Time.now + 6.months} 

and from jquery make wee function

 function readCookie(name) { var nameEQ = name + "=", ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i += 1) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return null; } 

and name it #in js

  if (readCookie('welcomed') == null){} 
+4
source

Ignore cookie from Javascript.

Using the question, which is referred to as duplicate, use a constant piece and on the first run install the class on your body from Rails (say first-run ). Then check your javascript and see if the body a first-run class. At this point, you can run javascript to run the code for the first time.

+3
source

Source: https://habr.com/ru/post/1339683/


All Articles