Block Pattern #3: Beautiful Object Initialization

There are a couple of ways to initialize an object in Ruby. Oftentimes, this is under the guise of applying configuration on an object. They usually mean the same thing. Here’s an example taken from the Twitter Ruby Gem:[4]

 client = Twitter::REST::Client.new ​do​ |config|
  config.consumer_key = ​"YOUR_CONSUMER_KEY"
  config.consumer_secret = ​"YOUR_CONSUMER_SECRET"
  config.access_token = ​"YOUR_ACCESS_TOKEN"
  config.access_token_secret = ​"YOUR_ACCESS_SECRET"
 end

See if you can guess at how this is implemented. Here’s a hint: consumer_key and the rest belong to accessors of Twitter::REST::Client. You’re going to build the bare minimum to get the preceding code to work. The code is ...

Get Mastering Ruby Closures 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.