ar_oo_select

Summary

A little gem that lets you execute lower-level ActiveRecord queries and access the resulting rows like you would by calling find_by_sql.

Rationale

Let's face it, ActiveRecord is slow. Sometimes you need a way to bypass ActiveRecord but still enjoy the typecasting and object-oriented goodness it provides. ar_oo_select allows you to do just that.

As you may or may not know, ActiveRecord gives you four methods to perform a low-level SQL query through the connection object itself:

  • connection.select_all
  • connection.select_rows
  • connection.select_one
  • connection.select_value

Likewise, ar_oo_select gives you four methods that are simply a wrapper for their builtin counterparts:

  • oo_select_all (aliased to oo_select since this is most common)
  • oo_select_rows
  • oo_select_one
  • oo_select_value

The difference is that 1) your query goes through AR's sanitize_sql method before reaching the connection methods and 2) the values in the result set are typecasted depending on what they look like (date, time, integer, float, or boolean). In the case of oo_select_all, the hashes that come from the result set are converted to special hashes whose values you can access using an object-oriented syntax (or openhashes for short), so it still feels like ActiveRecord. This is done using one of four libraries you may have installed, in this order:

Usage

All four methods receive the same arguments as find_by_sql: either a statement, or statement + bind variables. In addition, you can pass a second argument to specify whether the generated SQL should be sanitized. Taking oo_select_all as an example:

oo_select_all(query)
oo_select_all([query, vars])
oo_select_all(query, false) # don't sanitize sql
oo_select_all([query, vars], false) # don't sanitize sql

Installation

  1. Run gem install ar_oo_select (probably as root)
  2. Add config.gem 'ar_oo_select' to environment.rb
  3. Optionally run rake gems:unpack

Support

If you find any bugs with this plugin, feel free to:

Author/License

(c) 2009-2010 Elliot Winkler. See LICENSE for details.