Sha256: ab838144569337d2e9f76eaa3be8149a89e5e35a4276a8fb3289b37abd263369

Contents?: true

Size: 1018 Bytes

Versions: 1

Compression:

Stored size: 1018 Bytes

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mail_rotator-0.1.0 app/models/mailer_store.rb