Getting close to the database #2 – columns_as_array plugin

Sometimes you just don’t want to instantiate a bunch of ActiveRecord objects for getting some simple information from the database. You might save on memory and it’ll be faster.I made a very simple plugin that enables you to get all the values for one column in a table with a simple class method named according to the column – so for instance you can just say People.first_names and you will get all of them in a hash – key is the id, and value is the first_name.View it here – and install with:script/plugin install’s the README:ColumnAsArray=============This extension allows you to get all the values for a particular column from a table in one hash with a simple call using the column’s name in plural. The resulting hash keys are the ids, and the values are the column values.The idea is that in cases were only one column of data is needed from a table, but all or nearly all items in the table need to be read – perhaps for listing purposes – then we don’t need to instantiate a whole bunch of ActiveRecord objects just for this. This can save a great deal of heap space if there are many columns in a table.Example=======

>> Widget.names=> {7135=>"Big widget", 33=>"Old widget", 100=>"Fast widget">> Thing.updates_ats=> {2865=>"2008-02-04 09:57:55", 2344=>"2008-01-31 10:24:31", 1823=>nil, 260=>nil}

We use singularize to get the column name from the method name, and this works so that column names that are already plural need to have an extra ‘s’:

>> Client.format_choicess=> {7135=>"csv,xml", 33=>"xml", 100=>"csv,xls", 2110=>"csv", 167=>"xml"}