Ruby partition on arrays
In Ruby, the partition is a very useful method that you can use to filter some items in an array and that you need the ones that satisfy the condition and the ones that do not, and it takes a block of code and returns two arrays: the first contains the elements for which the block of code returns true, and the second contains the elements for which the block returns false.
Let's see an actual example:
def create_fake_emails_array
emails = []
10.times do |i|
emails << { email: "user#{i + 1}@mailinator.com" }
end
10.times do |i|
emails << { email: "user#{i + 1}@something.com" }
end
emails
end
my_emails = create_fake_emails_array
class EmailContactsWhitelistCleaner
attr_reader :email_recipients
def initialize(email_recipients)
@email_recipients = email_recipients
end
def get_white_list_collection
valid_recipients, invalid_recipients = partition_emails
log_black_list_email_recipients(invalid_recipients)
valid_recipients
end
private
def partition_emails
email_recipients.partition { |recipient| valid_recipient?(recipient[:email]) }
end
def valid_recipient?(email)
!email.match?('mailinator') || mailinator_white_list.include?(email)
end
def log_black_list_email_recipients(invalid_recipients)
return if invalid_recipients.empty?
email_list = invalid_recipients.map { |recipient| recipient[:email] }.join(',')
puts "The following emails are not in the whitelist: #{email_list}"
end
def mailinator_white_list
# ENV.fetch('MAILINATOR_WHITE_LIST', '').split(',')
'user1@mailinator.com,user2@mailinator.com,user3@mailinator.com'
end
end
service = EmailContactsWhitelistCleaner.new(my_emails)
puts service.get_white_list_collection