class Reminder def initialize @collection = reminder_collection end def count @collection.count end alias size count def candidates Candidate.includes(:recruiter).where(id: @collection.map { |row| row['id'] }) end def send_all candidates.each do |candidate| CandidateMailer.reminder(candidate).deliver_now flag_as_reminded candidate.id end end private def reminder_collection sql = "select c.id, c.test_hash, c.name, c.email, max(a.updated_at) last_updated from candidates c inner join answers a on a.candidate_id = c.id where completed = false and reminded = false group by c.id having MAX(a.updated_at) < DATE_SUB(NOW(), INTERVAL 24 HOUR);" ActiveRecord::Base.connection.exec_query(sql) end def flag_as_reminded candidate_id Candidate.find(candidate_id).update(reminded: true) end end