Adds methods to return attribute hashes rather than instantiated ActiveRecord objects. This is useful when working with large sets of records and you need the performance more than you need the convenience of your ActiveRecord methods.
The hashes that return are similar to the hash that returns with
ActiveRecord::Base#attributes
, except values are not
coerced (e.g., a tinyint column containing 1
will not be coerced into
true
). Strings, dates, and numbers will return as their appropriate
Ruby object. Booleans will return the underlying representation and
serialized objects will return as strings.
all_as_hashes
works similarly toall
, but returns the results as an array of hashes.first_as_hash
works similarly tofirst
, but returns a hash of the first matching record.
> User.where(:email => nil).all_as_hashes
=> [
{:id => 123, :name => "Joe User", :email => nil},
{:id => 456, :name => "Jane User", :email => nil}
]
> User.where(:email => nil).first_as_hash
=> {:id => 123, :name => "Joe User", :email => nil}
These methods are not for everyday use, but for when speed of execution is more important than convenience, like heavy-duty reporting or processing lots of existing records.
In one example, looping through 36,400 User records and accessing an
attribute used 32% less memory and performed 17% quicker using
all_as_hashes
over all
.
The equivalent methods are available in ActiveResource as well, providing similar benefits.
The hashes that return are essentially the xml or json data hashified.
all_as_hashes
works similarly toall
, but returns the results as an array of hashes.find_as_hashes
works similarly tofind
, but returns the results as an array of hashes.first_as_hash
works similarly tofirst
, but returns a hash of the first matching record.last_as_hash
works similarly tolast
, but returns a hash of the last matching record.
To enable the use of these methods, simply add this line to the top of your ActiveResource class.
require 'active_resource/find_as_hashes'
> User.all_as_hashes(:active => 1)
=> [
{:id => 123, :name => "Joe User", :active => 1,},
{:id => 456, :name => "Jane User", :active => 1}
]
> User.first_as_hash(:active => 1)
=> {:id => 123, :name => "Joe User", :active => 1}
Run tests with bundle exec rake test
(or just rake test
if you're
daring).