Tech thought and notes

Fun With Ruby Hashes - Initializing With a Block

Jan 1st, 2014

The alternate title for this post was Poor man’s email load balancer.

A less common method for creating and using Ruby hashes is to initialize the hash with a block. This allows you to return and/or assign a value for a missing key. You can think of this as a parallel to using method_missing in Ruby classes and modules.

So now we have a way of always returning a default value for a hash. Not very interesting in and of itself. What else could we do with our block backed hash?

A simple loadbalancer…

This is one of my favorite hacks. At MileMeter, we were using our Google Apps account to send email (reminders, confirmation emails, etc). At the time (not sure what the limit is now) we were limited to 500 emails per day from a single account. At some point, we started bumping up against the 500 email per day limit.

It was easy enough to create another email account to send emails through, but ActionMailer only provided a single configuration and we didn’t want to upgrade Google Apps for all MileMeter users because of a single account limitation.

John Riney and I looked at our options went in search of a solution which would allows us to send more emails without spending any additional money.

It was easy enough to create additional emails accounts. Armed with a Hash initialized with a block, we can now tell ActionMailer to pick a random user_name from a list of accounts each time it sent an email, thus effectively load-balancing our email.

Assuming the password is set the same for all accounts you want to use, when an email is sent, the user_name for the account is looked up and set to a different value every time, effectively a simple load-balancing technique.