Method Wrappers

Where you learn how to wrap a method inside another method—three different ways.

As the day draws to a close, you and Bill find yourselves stuck. Many methods in Bookworm rely on an open source library that retrieves a book’s reviews from Amazon’s website. The following code shows one example:

 def​ deserves_a_look?(book)
  amazon = Amazon.new
  amazon.reviews_of(book).size > 20
 end

This code works in most cases, but it doesn’t manage exceptions. If a remote call to Amazon fails, Bookworm itself should log this problem and proceed. You could easily add exception management to each line in Bookworm that calls deserves_a_look?—but there are tens of such lines, and you don’t want to change all of them.

To sum up the problem: ...

Get Metaprogramming Ruby 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.