public
Description: A Rails plugin that overrides the default select behavior of ActiveRecord
Homepage:
Clone URL: git://github.com/curt/paranoid_find.git

Paranoid Find

A plugin for Rails to override the default behavior of ActiveRecord.find.

Description

By default, the ActiveRecord.find method queries the database for all columns in an underlying table and exposes their contents as attributes of the objects it returns. On a wide table, this may be inefficient, especialy if only a few columns are needed in a typical query.

The ParanoidFind plugin overrides the default behavior of the ActiveRecord.find method to query only the primary key column of an underlying table. A new class method ActiveRecord.select is made available to specify other default columns, or all columns using the :all symbol, if desired. As before, full control of the columns selected is still available using the :select option of the ActiveRecord.find method.

The plugin works by reimplementing the private ActiveRecord.find_initial, ActiveRecord.find_every, and ActiveRecord.find_from_ids methods and adding an appropriate :select option, if one is not already defined.

Examples

Assuming ParanoidFind will be used on individual models

Define a model where ActiveRecord.find returns only the primary key column:

  class Model < ActiveRecord::Base
    include ParanoidFind
  end

Define a model where ActiveRecord.find returns only the id and name columns:

  class Model < ActiveRecord::Base
    include ParanoidFind
    select :id, :name
  end

Assuming ParanoidFind will be used on all models

In the configuration file, specify that all models use ParanoidFind:

  ParanoidFind.base_include

If all models to use ParanoidFind, go back to the default setting of returning all columns:

  class Model < ActiveRecord::Base
    select :all
  end

Column names

Column names can be strings or symbols, or a mixture of the two.

Testing

Testing the plugin requires the Shoulda plugin.

Credits

This plugin was inspired by a classroom discussion at the Advanced Rails Studio offered by Pragmatic Studio in Denver, Colorado, June 12-14, 2008.

License

Copyright © 2008 Curt A. Gilman, released under the MIT license