Skip to content

Instantly share code, notes, and snippets.

@supremebeing7
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supremebeing7/b34f32ff37489bf9c346 to your computer and use it in GitHub Desktop.
Save supremebeing7/b34f32ff37489bf9c346 to your computer and use it in GitHub Desktop.
Email Chunking for SMTP API
# This method separates emails into 1000 email chunks for bulk sending
# through an SMTP API such as SendGrid API
def self.chunk_emails(recipients)
if recipients.count < 1000
[recipients]
else
split_recipients = recipients.count.divmod(1000)
# Example, if recipients.count == 3200, then ...
quotient = split_recipients[0] # => 3
remainder = split_recipients[1] # => 200
chunks = []
(1..quotient).to_a.each_with_index do |el, ind|
starting = ind * 1000
ending = el * 1000
chunks[ind] = recipients[starting...ending]
end # This loop gives 1000 email chunks but does not handle any remaining
chunks[quotient] = recipients[(quotient * 1000)..-1]
# This line gets the remaining emails
# (in previous example, this would get the last 200 emails)
chunks
end
end
# REFACTORED TO ONE LINE
def self.chunk_emails(recipients)
chunks = recipients.each_slice(1000).to_a
end
# This would also work (rails only, ruby will not run this method)
# Plus I think it reads better
def self.chunk_emails(recipients)
chunks = recipients.in_groups_of(1000, false)
end
# As far as Benchmarking, after running about 25 tests, there's no clear winner. Each won about half the time.
# So, I'll stick with m chunk_emails method since it seems to me the most readable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment