Today I Learned

A Zero One initiative

Time to get .lazy, then .eager

.lazy loading

If you need to lazy load an associated set of data in an API client (or at any other time) in an object, you can use the .lazy method on an enumerator:

hogwarts.wizards = wizard_ids.lazy.map { |wizard_id| find_wizard(wizard_id) }

The above will return an Enumerator::Lazy that will only perform the map once the data is touched, for example by performing hogwarts.wizards.first.

Get .eager if necessary

There’s a snag here though, if you would like to perform a map on the actual data down the line, it will then return another Enumerator::Lazy, instead of performing your map.

To circumvent this, tack on a .eager to the end of the returned Enumerator::Lazy:

hogwarts.wizards = wizard_ids.lazy.map { |wizard_id| find_wizard(wizard_id) }.eager

This will then return the enumerated values when performing a .map down the line!

Looking for help? Each developer at Zero One has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.