Home > Net >  How to filter out inactive emails from an array of emails in a rails application?
How to filter out inactive emails from an array of emails in a rails application?

Time:10-15

I am currently working on a ticket where it asks me to filter out any inactive email to be sent to the recipient. Here is the method I am working on:

def self.delivering_email(message)
    return if email_to_be_delivered?(message.subject)
    
    email_list = message.to
    if email_list.is_a?(String)
      email_list = email_list.split(",").map(&:strip)
    end

    email_list.each { |email| 
      identity = Identity.find_by(email: email)
      next if identity.nil?
      # email_list.delete(email) unless identity.try(:preferred_user).active?
      email_list.select(email) if identity.try(:preferred_user).active?
    }
    
    message.to = email_list
    message.perform_deliveries = !email_list.empty?
  end

the "# email_list.delete(email) unless identity.try(:preferred_user).active?" I commented out because the QA mentioned that ONLY one inactive email filters out and does not fully filter other inactive emails in the array. I assumed instead of .delete I have to use .select but don't know if it works because I don't have any way to test and reproduce the error on my end, or how to implement it the right way.

Any help will be appreciated.

CodePudding user response:

You're trying to modify an array while you're iterating over it, that may lead to weird behavior. One option is to just use a separate array.

Since you are already iterating with email_list.each you can call next if the current email does not satisfy you, like you already do for identity.nil?.

So it may look smth like

valid_emails = []
email_list.each { |email|
  identity = Identity.find_by(email: email)
  next if identity.nil? || !identity.try(:preferred_user).active?
  valid_emails << email
end


message.to = valid_emails
  • Related