require 'active_record' module MailRotator class MailerStore < ActiveRecord::Base self.table_name = "mail_rotator_mailer_stores" validates :name, :limit, :sent_count, presence: true validates :name, uniqueness: true after_save :activate_next_mailer after_save :deactivate_other_mailers def activate self.update_attributes(active: true) end def increment new_count = self.sent_count + 1 self.update_attributes(sent_count: new_count, active: true) end def reset self.update_attributes(sent_count: 0, active: false) end def over_limit? sent_count >= limit end private def activate_next_mailer return if active next_mailer = self.class.where("id > ?", id).first next_mailer ||= self.class.first next_mailer.update_attributes(sent_count: 0, active: true) end def deactivate_other_mailers self.class.where("id != ?", id).update_all(active: false) unless self.active end end end