Goals
- Understand what Memoization is and when it can be useful.
- Understand the
@variable ||= computation
pattern. - Learn how to use the memoized Show archive.org snapshot gem.
- What are the advantages of a gem like
memoized
over the@variable ||=
syntax? - Why can it be dangerous to memoize class methods?
Why is it often fine to memoize instance methods?
Resources
- Speeding up Rails with Memoization Show archive.org snapshot
- 4 Simple Memoization Patterns in Ruby (And One Gem) Show archive.org snapshot
- Don't use the || operator to set defaults
Exercise
Write a class WebsiteSizer
that measures the number of characters in the given URL's HTML body:
website_sizer = WebsiteSizer.new
website_sizer.size_of('https://makandra.com') # => 27448
website_sizer.size_of('https://railslts.com') # => 2145364
You can use any library to perform the actual HTTP request.
The class should cache its results so subsequent calls for the same URLs return the HTML size instantly, without making an additional HTTP request.
Write two versions of WebsiteSizer
:
- A version that manually caches the results in some Ruby data structure
- A version that caches using the
memoized
gem.
Posted by Henning Koch to makandra Curriculum (2015-07-08 17:42)