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