Arel & ActiveRecord: The Definitive Guide to Ruby's SQL Manager
If you're a Ruby developer working with SQL, you might want to check out Jiří Pospíšil's definitive guide to Arel, the SQL manager for Ruby. It's one of those libraries that you use constantly and rely on heavily, even though you might not know much about how it works, or even that it exists. Pospíšil describes Arel as follows:
It’s all about providing frameworks with a way of building and representing SQL queries. It’s not the kind of library you would typically want to use directly (although you could as shown in a minute). Arel is meant to be the basic building block upon which frameworks build their own APIs that are more suitable for the end user.
One such framework, as most Ruby devs are certainly aware, is ActiveRecord, Rails' default ORM. Pospíšil uses ActiveRecord for most of his examples, and goes into great detail explaining the inner workings of Arel and, more importantly, Arel's relationship with ActiveRecord:
The interesting thing is the collaboration between Arel and ActiveRecord. Arel is technically independent from ActiveRecord but it needs to get the database details from somewhere and currently it uses ActiveRecord. More specifically, Arel requires ActiveRecord’s APIs. There’s even a fake ActiveRecord implementation, FakeRecord, that is used to run the Arel’s tests.
Pospíšil explores basic SELECT statements, various JOINs, the limitations of the technology, and more, pointing out the interactions between Arel and ActiveRecord for each. He evens walks you through working directly with the underlying Arel objects, even though that sort of cleverness isn't currently supported.
If you're interested in getting to know your Ruby in a bit more of an under-the-hood fashion, Pospíšil's guide to Arel is a great place to start.