Reputation: 4320
Hi Im trying to implement a countdown timer, I have an "oferts" model in my app, you can set the time it's gonna be available and there is where the countdown plays.
After a lot of research I found this Gem, it works like a charm, but Im facing a problem, how do I get the event when the countdown reaches cero?
I mean, my "oferts" model has a boolean attribute "active", I want when the countdown ends change the attribute "active" to false
how would you do it? any advice? is the gem Im using the correct one?
Thanks for your help
Upvotes: 0
Views: 1222
Reputation:
Great we in grupoly implemented such a system what you are describing.
But you are thinking it wrong, I will lead a solution for anybody that needs this.
First of all I would create a scope in the oferts model like this:
#ofert.rb
scope :are_ready_to_inactive, -> {
where(active: true).where('ends_at <= ?', Time.zone.now)
}
So I supose you have an attribute called ends_at
so we get all the oferts that their ends_at
is less than the current time, it means all the oferts that expired.
Then you just need to create a rake task for inactivate all those oferts that have expired:
#lib/tasks/oferts.rake
namespace :oferts do
desc "Inactive oferts with cron on certain time"
task inactivatethem: :environment do
Ofert.are_ready_to_inactive.find_each do |ofert|
ofert.update_attributes active: false
end
end
end
Great now if you run in your console rake oferts:inactivatethem
you will inactivate all the oferts that already expired, you can make run this rake task every minute for example using a gem like whenever gem
#config/schedule.rb
every 1.minute do
rake 'oferts:inactivatethem'
end
Now if you need to display the countdown in real time, you can use a jQuery plugin like jQueryCountDown, I think there is a gem ready for the asset pipeline, you just need to follow instructions there.
I want you to understand that countdown is only "visual" it means it is only for the user, it is a timer that only has sense on the client, in the backend you have your rake task that runs every minute looking for oferts that expired and inactivating them.
I wont give you details about how to show the timer because that is just jQuery stuff.
I hope this helps anyone.
Upvotes: 1