Attempting to revamp a straightforward cookie-based page counter for a paywall with the use of Rails built-in cookies functionality. The concept is simple: each time a new page is visited, increment the value of the 'count' cookie by one. When the visitor reaches a certain number of page views (X), trigger the display of the paywall. A snippet of code in a paywall.js file, utilizing jquery.cookie.js, achieves this:
$(document).ready(function () {
// create cookie
var visited = $.cookie('visited'); // initial value = 0
var pageTitle = document.title;
if (visited == 7) {
$("p.counter").html("From now on, you will always encounter fancybox upon your next visit!");
// open fancybox after 1 second on the 8th visit
setTimeout(function () {
$.fancybox.open({
href: "#inline"
});
}, 1000);
} else {
visited++; // increment visit counter
$("p.counter span").append(visited);
// update cookie value to match total visits
$.cookie('visited', visited, {
expires: 365, // set to expire in one year
path: "/"
});
return false;
}
}); // ready
The following code, placed in the application controller, almost achieves the desired outcome but utilizes session[:counter] for the page count. While the page count increments correctly, it resets to zero upon closing and reopening the browser:
before_filter :set_visitor_cookie
def set_visitor_cookie
cookies[:visits] = {
value: increment_counter,
expires: 1.year.from_now
}
end
def increment_counter
if session[:counter].nil?
session[:counter] = 0
end
session[:counter] += 1
end
The question remains - how can the increment_counter method or the set_visitor_cookie method be adjusted to simply increase the value by 1 upon each page view?