Code Blog: Sexy instance_eval proxies in Ruby 

Some of the most mind-blowing language features in popular Ruby libraries/frameworks are made possible through the use of delegate proxies: objects that invisibly intercept method and variable calls in your code and forward them to one or more receiver objects.

For example this pattern is used in ActiveRecord to provide association methods that behave like Enumerables sometimes, like scopes at other times, while also providing some association-specific tasks like build or clear. One attribute can behave like three things at once — an Array, a scope, and an association — because when you send it messages, you're actually talking to association proxy, a fourth kind of thing that serves as a kind of message bus between you and your data.

What I'm interested in right now is a simple, petty question: why is it that the block syntax in Sunspot — Mat Brown's fantastic DSL for working with Apache Solr — lets me use variables or methods from outside its scope, like controller params or model attributes, but Karel Minarek's ElasticSearch library Tire doesn't? Again, the answer is a proxy.

In this gist, I go through each part of the ContextBoundDelegate proxy from Sunspot, explain how it works, then use it to describe a zoo using sexy block syntax.