How do I set duration for my Product
object? So that, when a product is created by a user, it sets the JS counter to 1 day
and then destroys/inactivates the @product
when the clock runs out.
I know how to run this asynchronously, using Sidekiq. The thing is I don't know how to get ruby to work with my working client side JS countdown. And, how to tell Rails that every time a product is created it'd have a period of 1 day (perhaps a callback?).
def end_time
self.destroy in 1.days
self.update_attribute(:end_time, Time.now)
end
EDIT:
It throws an error for the view.
Illegal nesting: content can't be both given on the same line as %div and nested within it.
Here's the model.
#countdown{"data-created-at" => @product.created_at}
%digits
%span.days
%pcd DAYS
%digits
%span.hours
%pcd HRS
%digits
%span.minutes
%pcd MINS
%digits
%span.seconds
%pcd SECS
products.js
function getTimeRemaining(endtime){
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor( (t/1000) % 60 );
var minutes = Math.floor( (t/1000/60) % 60 );
var hours = Math.floor( (t/(1000*60*60)) % 24 );
var days = Math.floor( t/(1000*60*60*24) );
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime){
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock(){
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if(t.total<=0){
clearInterval(timeInterval);
}
}
updateClock();
var timeInterval = setInterval(updateClock,1000);
}
var deadline = 'December 15 2015 00:00:50 UTC+0200';
initializeClock('countdown', deadline);