AREL where() to sql

Sometimes you just want the SQL for a WHERE clause:

 > Post.send(:sanitize_sql, :title => "foo", :body => "bar")
 => "\"posts\".\"title\" = 'foo' AND \"posts\".\"body\" = 'bar'"

I’m working on a Rails 2 to Rails 3 upgrade (I know, just in time for Rails 4), and I’ve been annoyed by the fact that ActiveRecord kept spewing its log statements out to the terminal and not to the log file. After realizing this was not a commonly encountered problem, I realized the culprit was an old, out-dated plugin in vendor/plugins that was looking for a variable called RAILS_DEFAULT_LOGGER which no longer exists, and was then creating a new Logger that just writes to STDERR. Ditching the plugin solved my problem. Sane people probably remove / update their plugins first. For the rest of us, keep this in mind.

Active Record Model Adapters

I recently refactored some code in iNaturalist that fetches taxon names from external name providers like uBio and the Catalogue of Life. They return names and classification data that are similar but (of course) not identical to ActiveRecord models we use in iNat, so I figured I’d write adapters for them, and I thought a really smart solution would be to subclass the models themselves, simply overriding the attributes with getters that mined a private instance variable holding an XML response from one of the web services. Big mistake. ActiveRecord mixes in all kinds of magic into the models that doesn’t necessarily get passed on to child classes. I ran into all sorts of fun errors and problems until I remembered the Adapter implementation described here, which takes a much more sensible approach: don’t sublcass, and instead hold an internal copy of the adaptee, passing calls to anything you don’t want to override to the adaptee.

Read the rest of this entry »