Sha256: 25a29d09b65cec0f9b6d4e3ec4ed6b7df7e404a606f4395102f42b461279898d

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

require_relative "../../app/models/mailer_store"

module MailRotator
  module Switcher
    module_function

    def treat(klass)
      validate_constant
      validate_rows

      mailer = current_mailer
      mailer.public_send(mailer.over_limit? ? :reset : :increment)

      assign_mailer(klass, current_mailer)
    end

    def validate_constant
      return if Switcher.const_defined?("SMTP_SETTINGS")
      raise "MailRotator: MailRotator::Switcher::SMTP_SETTINGS is not defined. Refer to the README."
    end

    private
    module_function

    def validate_rows
      config_mailer_names = SMTP_SETTINGS.keys.sort
      db_mailer_names = MailerStore.pluck(:name).sort

      return if (config_mailer_names == db_mailer_names)
      raise "Please run 'rake db:migrate mail_rotator:update_rows' for RAILS_ENV=#{ENV['RAILS_ENV']}."
    end

    def assign_mailer(klass, mailer)
      hash = SMTP_SETTINGS[mailer.name]
      klass.smtp_settings = hash[:settings] || hash['settings']
    end

    def current_mailer
      mailer = active_mailer
      return mailer if mailer
      mailer = first_mailer
      first_mailer.activate
      first_mailer
    end

    def active_mailer
      MailerStore.where(active: true).first
    end

    def first_mailer
      MailerStore.first
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mail_rotator-0.1.0 lib/mail_rotator/switcher.rb